标签:
package Decorator;
// 被包装的物品,譬如超人 public class Person { private String name; public Person(String name){ this.name = name; } public Person(){}; public void show(){ System.out.println("被装饰的"+name); } } package Decorator; public class Sneakers extends Finery{ @Override public void show() { // TODO Auto-generated method stub System.out.println("破球鞋"); super.show(); } } package Decorator; public class TShirts extends Finery{ @Override public void show() { // TODO Auto-generated method stub System.out.println("大T恤"); super.show(); } } package Decorator; public class BigTrouser extends Finery{ @Override public void show() { // TODO Auto-generated method stub System.out.println("跨裤"); super.show(); } } package Decorator;
// 从哪个方面包装,譬如服饰 public class Finery extends Person { protected Person p = null; public void decorator(Person p){ this.p = p; } public Finery(){} @Override public void show() { if(p!=null){ p.show(); } } } package Decorator; public class testDecorator{ /** * @param args */ public static void main(String[] args) { // TODO Auto-generated method stub Person p = new Person("nigel"); BigTrouser bt = new BigTrouser(); TShirts ts = new TShirts(); Sneakers sn = new Sneakers(); sn.decorator(p); ts.decorator(sn); bt.decorator(ts); bt.show(); //ts.show(); } }
装饰者模式:
装饰什么?
用什么装饰?
装饰的顺序由客户端定,即main方法里的顺序。
最主要的应该是定位上面两个问题,对号入座了,那你的场景就能用这个模式了。
标签:
原文地址:http://www.cnblogs.com/wade-luffy/p/5670023.html