ispsh 发表于 2015-6-16 11:52:02

开放-封闭原则OCP(Open-Close Principle)

Ivar Jacobson:任何系统在其生命周期都会变化,如果我们期望我们开发的系统不会在第1版后就被抛弃,就必须牢记这一点.
Open-Closed Principle
1.Open(Open for extension)
模块的行为必须是开放的,支持扩展的,而不是僵化的.
2.Closed(Closed for modification)
对模块进行扩展时,不应该影响或大规模影响已有模块的其他部分.



class Cllient
{
   Server server;
   void GetMessage()
   {
      server.Message();
   }
}

class Server
{
   //
   void Message();
}
//上面这个例子就是既不开放也不封闭的,因为Client和
//Server都是具体类,如果我要Client使用不同的一个
//Server类那就要修改革者Client类中所有使用Server类的地方为新的Server类.
class Client
{
   ClientInterface ci;
   public void GetMessage()
   {
       ci.Message();
   }
   public void Client(ClientInterface paramCi)
   {
       ci=paramCi;
   }
}
interface ClientInterface
{
    public void Message();
    //other function
}

class Server:ClientInterface
{
    public void Message();
}

//那么在主函数(或主控端)则
public static void Main()
{
   ClientInterface ci = new Server();
   //在上面如果我有新的Server类只要替换Server()就行了.
   Client client = new Client(ci);
   client.GetMessage();
}


我们看到Server类是从ClientInterface继承的,不过ClientInterface却不叫ServerInterface叫ClientInterface,原因是我们希望对Client来说ClientInterface是固定下来的,变化的只是Server.开放了,也封闭了:)这实际上就变成了一种策略模式(Gof Strategy).
Bob还提到了一种实现ocp的方法,那就是Template Method


absract class policy
{
    private int[]={1,1234,1234,1234,132};
    public bool Sort()
    {
          SortImp();
    }
    protected virtual SortImp()
   {

   }
}

class bubbleimp:policy
{
   protected override virtual SortImp()
   {
       //冒泡排序
   }
}
class bintreeimp:policy
{
    protected overide virtual SortImp()
   {
       //二分法排序
   }
}

//Other Class:policy
public static void Main()
{
   policy sort =new bintreeimp();
   sort.Sort();
   
}

同时,我们应该仅对程序中呈现频繁变化的那部分做抽象.不成熟的抽象和没有抽象一样的坏.
页: [1]
查看完整版本: 开放-封闭原则OCP(Open-Close Principle)