Open-Closed Principle
来源:互联网 发布:二建做题软件哪个好 编辑:程序博客网 时间:2024/05/17 01:15
开放封闭原则
开放封闭原则(OCP,Open Closed Principle)是所有面向对象原则的核心。软件设计本身所追求的目标就是封装变化、降低耦合,而开放封闭原则正是对这一目标的最直接体现。其他的设计原则,很多时候是为实现这一目标服务的,例如以Liskov替换原则实现最佳的、正确的继承层次,就能保证不会违反开放封闭原则。
关于开放封闭原则,其核心的思想是:
软件实体应该是可扩展,而不可修改的。也就是说,对扩展是开放的,而对修改是封闭的。 因此,开放封闭原则主要体现在两个方面:
对扩展开放,意味着有新的需求或变化时,可以对现有代码进行扩展,以适应新的情况。
对修改封闭,意味着类一旦设计完成,就可以独立完成其工作,而不要对类进行任何修改。
示例
面向抽象编程,计算一个圆柱体体积,分矩形底和圆形底。
Geometry.java
package com.ab;public abstract class Geometry { public abstract double getArea();}
Circle.java
package com.ab;//第一个子类public class Circle extends Geometry{ double r; Circle(double r){ this.r = r; } public double getArea(){ return (3.14*r*r); }}//第二个子类class Rectangle extends Geometry{ double a; double b; public Rectangle(double a, double b) { this.a = a; this.b = b; } @Override public double getArea() { // TODO Auto-generated method stub return a*b; }}
Pillar.java
package com.ab;public class Pillar { Geometry bottom; double height; Pillar(Geometry bottom,double height){ this.bottom =bottom; this.height = height; } public double getVolume(){ return bottom.getArea()*height; }}
Application.java
package com.ab;public class Application { public static void main(String[] args) { Pillar pillar; Geometry bottom; bottom = new Rectangle(12, 22); pillar = new Pillar(bottom, 58); System.out.println("矩形底的圆柱体体积"+pillar.getVolume()); bottom = new Circle(10); pillar = new Pillar(bottom, 58); System.out.println("圆形底的圆柱体体积"+pillar.getVolume()); }}
矩形底的圆柱体体积15312.0
圆形底的圆柱体体积18212.0
UML类图
该设计中Geometry和Pillar类就是系统中对修改关闭的部分,而Geometry的子类就是对扩展开放的部分,当向系统再增加任何Geometry的子类时(对扩展开放),不必修改Pillar类,就可以使用Pillar创建出具有Geometry的新子类指定的底的柱体。
-java程序设计实用教程 p105
0 0
- Open-Closed Principle,OCP
- Open-Closed Principle
- 开闭原则(open-closed principle)
- 开闭原则(Open-Closed Principle)
- OCP简介(OCP--Open-Closed Principle)
- OCP(Open-Closed Principle)开放封闭原则
- 开放闭合原则--Open-Closed Principle
- “开-闭”原则(Open-Closed Principle)
- Open-Closed Principle 开-闭原则
- “开闭原则”(Open-Closed Principle,OCP
- “开-闭”原则(Open-Closed Principle)
- 开放关闭原则【The Open Closed Principle】
- 开放--封闭原则(Open Closed Principle,OPC)
- 开放关闭原则(Open-Closed Principle)
- 开-闭原则(OCP - Open-Closed Principle )
- Open Closed Principle 开放封闭原则
- “开-闭”原则 (Open-Closed principle, OCP)
- 第九章 OCP:The Open-Closed Principle(开闭原则)
- android3.0属性动画详解
- PL/SQL Developer Version 9.0.6.1665 破解注册码
- 数据库改编码教程
- Android TextView(EditView)文字底部或者中间 加横线
- C语言关键字:static,const,inline,volatile与assert()等
- Open-Closed Principle
- oracle审计
- text跑马灯效果
- 机器学习中的相似度度量(1)
- 互联网是追求新技术还是追求新创业呢?
- 证明多维数组的线性存储
- L0/L1/L2范数的联系与区别
- Myeclipse发布jar包
- 在Android开发中使用MVP模式