Open-Closed Principle

这个原则最早是由Bertrand Meyer提出,英文的原文是:Software entities should be open for extension,but closed for modification.意思是说,一个软件实体应当对扩展开放,对修改关闭.也就是说,我们在设计一个模块的时候,应当使这个模块可以在不被修改的前提下被扩展,换句话说就是,应当可以在不必修改 源代码的情况下改变这个模块的行为.

  满足OCP的设计给系统带来两个无可比拟的优越性.
  1.通过扩展已有的软件系统,可以提供新的行为,以满足对软件的新需求,使变化中的软件系统有一定的适应性和灵活性.
  2.已有的软件模块,特别是最重要的抽象层模块不能再修改,这就使变化中的软件系统有一定的稳定性和延续性.
  例如:
  编程模式中的工厂模式的“工厂方法”支持OCP原则

转载于:https://my.oschina.net/wangfree/blog/79429

3)A digital clock consists of a screen to display the time and a dial for setting in turn the year, month, day, hour and minute. Twisting the dial to the left reduces by one the value being changed but twisting it to the right increases it by one. Pushing the dial alters which value is being adjusted. At first, it is the year but after the dial is pushed once, it is the month, then after the dial is pushed again, it is the day and so on. Imagine the clock is represented by a class with attributes year, month, day etc. The following is what the code for a method rotateDialLeft() might look like. public void rotateDialLeft() { if (mode == YEAR_MODE) { year--; } else if (mode == MONTH_MODE) { month--; } else if (mode == DAY_MODE) { day--; } else if (mode == HOUR_MODE) { hour--; } else if (mode == MINUTE_MODE) { minute--; } } The code for rotateDialRight() is similar. Apply the Open-Closed Principle to explain why the above code is unsatisfactory from the design viewpoint, considering the possibility of future change to the code, giving an example of such a change. 5)Give the code required for the classes introduced in question 3), focusing on the code for a method selectState() which changes the value that is being adjusted from years to months. Make it clear in which classes the code is to be found. Assume the existence of other methods that are needed such as getMonthSetUpState(). 8)Suppose that in a multiplayer role-playing game, a class Client has a dependency to an interface Fighter with public methods attack(), defend() and escape(). The game designer now wishes for Client to use a class Wizard with three different but equivalent public methods castDestructionSpell(), shield() and portal(). Explain how it is possible to do this using an appropriate design pattern.
06-03
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值