设计模式--开闭原则

开闭原则:指的是一个软件实体应对对扩展开发,对修改关闭(Software entities should be open for extension, but closed for modification)。这个原则是说在设计一个模块的时候,应对使这个模块可以在不被修改的前提下被扩展,换言之,应对可以不必修改源代码的情况下改变这个模块的行为。
根据开闭原则,在设计一个软件系统模块(类,方法)的时候,应该可以在不修改原有的模块(修改关闭)的基础上,能扩展其功能(扩展开放)。
- 扩展开放:某模块的功能是可扩展的,则该模块是扩展开放的。软件系统的功能上的可扩展性要求模块是扩展开放的。
- 修改关闭:某模块被其他模块调用,如果该模块的源代码不允许修改,则该模块修改关闭的。软件系统的功能上的稳定性,持续性要求是修改关闭的。

1.interface Fruit   
2.{   
3.    public void plant();   
4.    public void blossom();   
5.    public void outcome();   
6.}   
1.class Apple implements Fruit   
2.{   
3.    Apple(){this.plant();}   
4.    public void plant(){System.out.println("Plant a apple");};   
5.    public void blossom(){System.out.println("Apple blossomed");};   
6.    public void outcome(){System.out.println("Apple outcomed");};   
7.}   
1.interface gardenerBase //Garden,是不能改变的.以后增加一个水果只需要 再写个类继承它!   
2.{   
3.    public Fruit getFruit();   
4.}   
5.class AppleGardener implements gardenerBase//种植Apple的Garden   
6.{   
7.    private static AppleGardener singleton;   
8.    private AppleGardener(){;}   
9.    public static AppleGardener getGardener()   
10.    {   
11.        if(singleton==null)   
12.        singleton = new AppleGardener();   
13.        return singleton;   
14.    }      
15.    public Fruit getFruit()   
16.    {   
17.        return new Apple();   
18.    }   
19.}   
1.public class MyFirstOCPJAVA   
2.{   
3.    public static void main(String []a)   
4.    {   
5.        Fruit tempApple;   
6.        gardenerBase appleGarden = AppleGardener.getGardener();   
7.        tempApple = appleGarden.getFruit();   
8.  
9.        Fruit tempPear;   
10.        gardenerBase pearGarden = PearGardener.getGardener();   
11.        tempPear = pearGarden.getFruit();   
12.    }   
13.}  

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值