IT博客汇
  • 首页
  • 精华
  • 技术
  • 设计
  • 资讯
  • 扯淡
  • 权利声明
  • 登录 注册

    [原]使用面向对象重构之-从过程式设计到面向对象

    csharp25发表于 2017-02-23 22:52:36
    love 0
    写在前面
    最近两年接手的几个C#和java的project,发现目前很多程序员的编程思维中,几乎没有用到对象和抽象的力量,扩展和修改起来非常困难,甚至阅读都有困难。决定写一个面向对象基础专栏,笔者希望能把这几次重构中所发现的问题,尤其是涉及到面向对象几个重要的基础知识说明清楚,让初学者能够明白并应用到项目中去。本系列文章的所有示例代码为C#。


    第一步:从过程设计到对象
    以下是一种典型的面向过程设计的编程风格。类名以management,Processing为结尾的通常都是过程式设计产生的。


     
    public class LeaveManagement
        {
            public IEnumerable<Leave> GetLeavesByUserId(string userId)
            {
                ...
            }
    
    
            public Leave GetLeave(Guid id)
            {
                ...
            }
            public bool ApproveLeave(Leave leave)
            {
                ...
            }
            public bool RejectLeave(Leave leave)
            {
                ...
            }
    
    
            // ...
        }
    
    
        public class Leave
        {
            public Guid Id { get; set; }
            public string Title { get; set; }
            public string Description { get; set; }
            public DateTime AppliedAt { get; set; }
            public bool Approved { get; set; }
    
    
            public override string ToString()
            {
                return string.Format("title:{0}, description:{1}", Title, Description);
            }
        }




    引入对象。
     public class Leave
        {
            public Guid Id { get; set; }
            public string Title { get; set; }
            public string Description { get; set; }
            public DateTime AppliedAt { get; set; }
            public bool Approved { get; set; }
    
    
            public override string ToString()
            {
                return string.Format("title:{0}, description:{1}", Title, Description);
            }
        }
    
    
        public enum Gender
        {
            M,
            F
        }
        public class Employee 
        {
            public string FirstName { get; set; }
            public string LastName { get; set; }
            public Gender Gender { get; set; }
            public DateTime JoinedAt { get; set; }
            // ...
    
    
            public bool ApplyLeave(Leave leave)
            {
                ...
            }
    
    
            public IEnumerable<Leave> GetMyLeaves()
            {
                
            }
        }
    
    
        public class Manager : Employee
        {
            public bool ApproveLeave(Leave leave)
            {
                ...
            }
    
    
            public bool RejectLeave(Leave leave)
            {
                ...
            }
        }




    首先以上代码创建了若干类,
    leave:请假对象
    employee:员工对象
    manager:经理对象


    其次做了方法提取。把management类中的方法分配在了不同的对象中。这样就完成了重构的第一步,也是我们开始使用OO力量的开始。
    在接下来的文章中,需求会稍微有些变化,会介绍如何使用不同的面向对象技巧来应对变化,适应变化。


沪ICP备19023445号-2号
友情链接