python 开闭原则_设计模式笔记:开闭原则(OCP,The Open-Closed Principle)

1. 开闭原则概述

开闭原则(OCP,The Open-Closed Principle)两个主要特征:

(1)对扩展开放(open for extension):模块的行为的可以扩展的,当应用的需求改变时,可以对模块进行扩展。

(2)对修改关闭(closed for modification):对模块进行扩展时,不必改动模块的源代码

开闭原则是面向对象设计中可复用设计的基石。

2. 开闭原则的实现

开闭原则实现关键:抽象。

抽象基类:把系统的所有可能的行为抽象成一个抽象底层,这个抽象底层规定出所有的具体实现必须提供的方法的特征。作为系统设计的抽象层,要预见所有可能的扩展,从而使得在任何扩展情况下,系统的抽象底层不需修改。

派生类:从抽象基类派生一个或多个新的具体实现,可以扩展基类的行为,系统设计对扩展开放。

3. 如何使用开闭原则

抽象约束:

(1)通过接口或者抽象类约束扩展,对扩展进行边界限定,不允许出现在接口或抽象类中不存在的public方法;

(2)参数类型、引用对象尽量使用接口或者抽象类,而不是实现类;

(3)抽象层尽量保持稳定,一旦确定即不允许修改。

让设计对于最有可能发生的变化遵循OCP原则。遵循OCP原则的代价是很昂贵的,创建适当的对象需要开发时间和精力,抽象增加软件复杂度。把OCP应用限定在最有可能发生的变化上。

4. 开闭原则的优点

(1)可复用性

(2)可维护性

5.开闭原则重构

6. 开闭原则示例

Shape.cs

usingSystem;usingSystem.Collections.Generic;usingSystem.Linq;usingSystem.Text;namespaceDesignPatterns.OpenClosedPrinciple

{public abstract classShape

{protected string_name;public Shape(stringname)

{this._name =name;

}///

///面积///

///

public abstract doubleArea();///

///显示///

public abstract voidDisplay();

}

}

Rectangle.cs

usingSystem;usingSystem.Collections.Generic;usingSystem.Linq;usingSystem.Text;namespaceDesignPatterns.OpenClosedPrinciple

{///

///矩形///

public classRectangle : Shape

{private double_width;private double_height;public Rectangle(string name, double width, doubleheight)

:base(name)

{this._width =width;this._height =height;

}public override doubleArea()

{return _width *_height;

}public override voidDisplay()

{

Console.WriteLine("{0} 长:{1},宽:{2},面积:{3}", _name, _width, _height, this.Area());

}

}

}

Circle.cs

usingSystem;usingSystem.Collections.Generic;usingSystem.Linq;usingSystem.Text;namespaceDesignPatterns.OpenClosedPrinciple

{///

///圆形///

public classCircle : Shape

{private double_radius;public Circle(string name, doubleradius)

:base(name)

{this._radius =radius;

}public override doubleArea()

{return Math.Round(Math.PI * _radius * _radius, 2);

}public override voidDisplay()

{

Console.WriteLine("{0} 半径:{1},面积:{2}", _name, _radius, this.Area());

}

}

}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值