1. 程式人生 > >大話設計模式3 裝飾模式 的java程式碼實現

大話設計模式3 裝飾模式 的java程式碼實現

1,Person類(ConcreteComponent)
package yx.designpattern.decorator;

//Person類(ConcreteComponent)
public class Person {
	private String name;

	public Person(){
		
	}
	
	public Person(String name) {
		this.name = name;
	}
	
	public void show(){
		System.out.println("裝扮者:"+this.name);
	}
	

}

2,服飾類(Decorator)

package yx.designpattern.decorator;

//服飾類(Decorator)
public class Finery extends Person {
	protected Person component;
	
	//打扮
	public void decorate(Person component){
		this.component=component;
	}

	@Override
	public void show() {
		if(component!=null){
			component.show();
		}
	}
}

3,具體服飾類(ConcreteFinery)
package yx.designpattern.decorator;

//具體服飾類(ConcreteFinery)
public class ConcreteFineryA extends Finery {
	@Override
	public void show() {
		super.show();
		System.out.println("已裝扮服飾A");
	}

}
package yx.designpattern.decorator;
//具體服飾類(ConcreteFinery)
public class ConcreteFineryB extends Finery {
	@Override
	public void show() {
		super.show();
		System.out.println("已裝扮服飾B");
	}

}

package yx.designpattern.decorator;
//具體服飾類(ConcreteFinery)
public class ConcreteFineryC extends Finery {
	@Override
	public void show() {
		super.show();
		System.out.println("已裝扮服飾C");
	}

}
package yx.designpattern.decorator;
//具體服飾類(ConcreteFinery)
public class ConcreteFineryD extends Finery {
	@Override
	public void show() {
		super.show();
		System.out.println("已裝扮服飾D");
	}

}


package yx.designpattern.decorator;
//具體服飾類(ConcreteFinery)
public class ConcreteFineryE extends Finery {
	@Override
	public void show() {
		super.show();
		System.out.println("已裝扮服飾E");
	}

}


4,客戶端測試類

package yx.designpattern.decorator;

public class Test {
	public static void main(String[] args) {
		Person p1=new Person("小菜");
		Finery f1=new ConcreteFineryA();
		Finery f2=new ConcreteFineryB();
		Finery f3=new ConcreteFineryC();
		
		f1.decorate(p1);
		f2.decorate(f1);
		f3.decorate(f2);
		
		f3.show();
		
		
		Person p2=new Person("大鳥");
		Finery f4=new ConcreteFineryD();
		Finery f5=new ConcreteFineryE();
		
		f4.decorate(p2);
		f5.decorate(f4);
		
		f5.show();
		
		
		Person p3=new Person("路人");
		
		f5.decorate(p3);//可以按照任何順序,任何組合方案進行組合
		f2.decorate(f5);
		f4.decorate(f2);
		f1.decorate(f4);
		f3.decorate(f1);
		f3.show();
		
	}
}