Java设计模式 - 装饰器模式(一)

结构型模式——装饰器模式

概念:将多件服饰组装好,再一次性穿上去。

代码:

package com.lux.dec;

public class Person {
	private String name;

	public Person() {
	}

	public Person(String name) {
		this.name = name;
	}

	public void show()
	{
		System.out.println("装扮的"+name);
	}
}
package com.lux.dec;

public class Finery extends Person {

	protected Person comp;
	public int rs=-1;
	
	public void decorate(Person comp)
	{
		this.comp=comp;
	}
	
	@Override
	public void show() {
		if(comp!=null)
			comp.show();
	}
	
	public void showRs()
	{
		System.out.println("Finery == "+rs);
	}
}
package com.lux.dec;

public class Kua extends Finery {
	@Override
	public void show() {
		System.out.println("Kua");
		super.show();
	}
}


package com.lux.dec;

public class TShirt extends Finery {
	@Override
	public void show() {
		System.out.println("T-shirt");
		super.show();
	}
	
	@Override
	public void showRs() {
		System.out.println("TShirt == "+rs);
		super.showRs();
	}
}
package com.lux.dec;

public class Test {

	public static void main(String[] args) {
		Person pc=new Person("me");
		Kua kua=new Kua();
		TShirt ts=new TShirt();
		
		kua.decorate(pc);
		ts.decorate(kua);
		
		ts.show();
		
		ts.rs=10;
		ts.showRs();
	}
}
Console:
T-shirt
Kua
装扮的me

TShirt == 10
Finery == 10

Ps:如果子类继承父类时,若有属性被继承下来并且在子类中修改属性,则父类的 super.属性 也将会是子类修改好的值。

你可能感兴趣的:(#,Java,#,设计模式)