1. 程式人生 > >java設計模式--裝飾者模式

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

照例搬一篇文章連線,我一般會選擇帶有uml圖的 方便理解,我只貼程式碼,因為我覺得別人理解的比我透徹,寫的比我好 http://www.cnblogs.com/stonefeng/p/5679638.html

裝飾者模式可以給物件新增一些額外的東西,設計模式那種書中舉例是星巴克的例子,如果每一種做法都寫一個類的話大概會爆炸,所以選擇靈活的方式

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

public abstract class Component {

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

public String getDesc() {
return desc;
}

public abstract int price();

}

2.被裝飾者

public class ACupCoffe extends Component{

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

}

3.裝飾者

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());
}

}