裝飾模式

其通用類圖源碼如下:

public abstract class Component {
public abstract void doSomething();
}
public class ConcreteComponent extends Component{
@Override
public void doSomething() {
// TODO Auto-generated method stub
System.out.println("this is a ConcreteComponent");
}
}
public abstract class Decrator extends Component{
private Component component = null;
public Decrator(Component com){
this.component = com;
}
@Override
public void doSomething(){
this.component.doSomething();
}
}
public class ConcreteDecrator1 extends Decrator{
public ConcreteDecrator1(Component com) {
super(com);
// TODO Auto-generated constructor stub
}
public void doSomething() {
// TODO Auto-generated method stub
this.method1();
super.doSomething();
}
private void method1(){
System.out.println("this is a ConcreteDecrator");
}
}
public class ConcreteDecrator2 extends Decrator{
public ConcreteDecrator2(Component com) {
super(com);
// TODO Auto-generated constructor stub
}
public void doSomething(){
super.doSomething();
this.method2();
}
private void method2(){
System.out.println("this is another ConcreteDecrator");
}
}
public class Client {
/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
Component component = new ConcreteComponent();
component = new ConcreteDecrator1(component);
component = new ConcreteDecrator2(component);
component.doSomething();
}
}
View Code
裝飾模式的應用
最近剛剛過了雙十一的網上購物狂潮,購買的商品也萬裡迢迢的飛奔而來,拿到快遞那一刻的喜悅簡直感覺自己就是世界上最幸福的,然而如果你買的是服裝,相信你一定深有體會,為什麼自己穿上就沒有那種感覺了呢,冥思苦想,應該是商家對服裝的裝飾比較到位,下面我們就解析一下這種“差距”。


public abstract class Clothes {
//展示服裝信息
public abstract void parameter();
}
public class Coat extends Clothes{
@Override
public void parameter() {
// TODO Auto-generated method stub
System.out.println("this is a Coat");
System.out.println("It's size is XL");
System.out.println("It's color is dark blue");
}
}
public abstract class Decrator extends Clothes{
private Clothes clothes = null;
public Decrator(Clothes clothes){
this.clothes = clothes;
}
@Override
public void parameter(){
this.clothes.parameter();
}
}
public class Model extends Decrator{
public Model(Clothes clothes) {
super(clothes);
// TODO Auto-generated constructor stub
}
public void parameter(){
this.method2();
super.parameter();
}
private void method2(){
System.out.println("A clothes model wears the coat");
}
}
public class Scarf extends Decrator{
public Scarf(Clothes clothes) {
super(clothes);
// TODO Auto-generated constructor stub
}
public void parameter() {
// TODO Auto-generated method stub
this.method1();
super.parameter();
}
private void method1(){
System.out.println("this is a scarf to decrate the coat");
}
}
public class Client {
/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
Clothes clothes = new Coat();
clothes = new Scarf(clothes);
clothes = new Model(clothes);
clothes.parameter();
}
}
View Code
可憐了我們這些小白用戶,不知道還能這麼玩,藍瘦香菇。