java設計模式--裝飾者模式

照例搬一篇文章鏈接,我通常會選擇帶有uml圖的 方便理解,我只貼代碼,由於我以爲別人理解的比我透徹,寫的比我好 http://www.cnblogs.com/stonefeng/p/5679638.htmlhtml

裝飾者模式能夠給對象添加一些額外的東西,設計模式那種書中舉例是星巴克的例子,若是每一種作法都寫一個類的話大概會爆炸,因此選擇靈活的方式設計模式

1.建立抽象類,定義基本的行爲,裝飾者和被裝飾着都去繼承他ide

public abstract class Component {this

public String desc = "我是抽象組件,他們的共同父類";

public String getDesc() {
return desc;
}

public abstract int price();

}設計

2.被裝飾者htm

public class ACupCoffe extends Component{對象

public ACupCoffe() {
desc = "一杯咖啡";
}
@Override
public int price() {
// TODO Auto-generated method stub
return 10;
}blog

}繼承

3.裝飾者get

public abstract class Decorator extends Component{

public abstract String getDesc();
}

4.具體裝飾者1

public class Coffee extends Decorator{

private Component acupcoffe;

public Coffee(Component acupcoffe) {
this.acupcoffe = acupcoffe;
}
@Override
public String getDesc() {
// TODO Auto-generated method stub
return acupcoffe.getDesc() + "咖啡";
}

@Override
public int price() {
// TODO Auto-generated method stub
return acupcoffe.price() + 10;
}

}

5.具體裝飾者2

public class Sugar extends Decorator{

private Component acupcoffe;
public Sugar(Component aCupCoffe) {
this.acupcoffe = aCupCoffe;
}
@Override
public String getDesc() {

return acupcoffe.getDesc() + "糖";
}

@Override
public int price() {
// TODO Auto-generated method stub
return acupcoffe.price() + 10;
}

}

6.客戶端

public class Client {

public static void main(String[] args) {
Component aCupCoffe = new ACupCoffe();

aCupCoffe = new Sugar(aCupCoffe);
System.out.println(aCupCoffe.getDesc());
System.out.println(aCupCoffe.price());

aCupCoffe = new Coffee(aCupCoffe);
System.out.println(aCupCoffe.getDesc());
System.out.println(aCupCoffe.price());
}

}

相關文章
相關標籤/搜索