设计模式3:装饰模式
這種模式創(chuàng)建了一個(gè)裝飾類,用來(lái)包裝原有的類,并在保持類方法簽名完整性的前提下,提供了額外的功能。
意圖:動(dòng)態(tài)地給一個(gè)對(duì)象添加一些額外的職責(zé)。就增加功能來(lái)說(shuō),裝飾器模式相比生成子類更為靈活。
主要解決:一般的,我們?yōu)榱藬U(kuò)展一個(gè)類經(jīng)常使用繼承方式實(shí)現(xiàn),由于繼承為類引入靜態(tài)特征,并且隨著擴(kuò)展功能的增多,子類會(huì)很膨脹。
為了避免子類數(shù)量的快速膨脹,我們可以用裝飾模式為對(duì)象動(dòng)態(tài)的增加功能。
這些功能應(yīng)該是沒(méi)有相互關(guān)聯(lián)和先后順序的。
舉例來(lái)說(shuō),一個(gè)人可以穿各種不同的裝扮,如果為每套打扮生成一個(gè)子類,那么子類的數(shù)量將爆炸。
可以將裝飾模式應(yīng)用進(jìn)來(lái),使用衣物裝飾人。
來(lái)看UML圖:
Component類是公共基類,定義了show方法。
Person類繼承Component類,實(shí)現(xiàn)show方法。
Cloth對(duì)象將Component類作為其實(shí)例變量。
Trouser和TShirts類實(shí)現(xiàn)了show方法。
來(lái)看具體代碼:
public abstract class Component {public abstract void show(); }Component定義一個(gè)虛方法。
public class Person extends Component {private String name = null;public Person(String name) {this.name = name;}public void show() {System.out.println("我是" + name);} }Person實(shí)現(xiàn)了這個(gè)虛方法。
public class Cloth extends Component {protected Component component = null;public Cloth(pers.zcy.decorator.Component component) {super();this.component = component;}@Overridepublic void show() {if(component != null){component.show();}}}Cloth類是裝飾器的基類,其中包含一個(gè)Component實(shí)例對(duì)象,在show中調(diào)用這個(gè)實(shí)例對(duì)象的show方法。
public class Trouser extends Cloth {public Trouser(Component component) {super(component);// TODO Auto-generated constructor stub}@Overridepublic void show(){super.show();System.out.println("我穿了褲子");} }public class TShirts extends Cloth {public TShirts(Component component) {super(component);}@Overridepublic void show(){super.show();System.out.println("我穿了T恤");} }這兩個(gè)類重寫(xiě)show方法,同時(shí)顯式調(diào)用父類方法。
public class DecoratorDemo {public static void main(String[] args) {Person person = new Person("Mike");Cloth tshirts = new TShirts(person);Cloth trousers = new Trouser(tshirts);trousers.show();} }
轉(zhuǎn)載于:https://www.cnblogs.com/zcy-backend/p/6670652.html
總結(jié)
以上是生活随笔為你收集整理的设计模式3:装饰模式的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問(wèn)題。
- 上一篇: 关于void main()的误区
- 下一篇: java 保护内存操作的方法