`
xiaoy2002
  • 浏览: 5467 次
  • 性别: Icon_minigender_1
  • 来自: 杭州
最近访客 更多访客>>
社区版块
存档分类
最新评论

装饰模式

 
阅读更多
装饰模式,利用了setComponent来对对象进行包装。
class Person {
	private String name;
	public Person(){}
	public Person(String name){
		this.name = name;
	}
	
	public void show() {
		System.out.println("装扮的" + name);
	}
}

// 装饰类
class Decorator extends Person{
	protected Person person;
	
	public void setComponent(Person person){
		this.person = person;		
	}
	
	public void show(){
		if(person != null)
			person.show();
	}
}

// 不同的装饰
class Tshirts extends Decorator{
	public void show(){
		System.out.print("T恤  ");
		super.show();
	}
}
class BigTrouser extends Decorator{
	public void show(){
		System.out.print("垮裤  ");
		super.show();
	}	
}
class Sneakers extends Decorator{
	public void show(){
		System.out.print("破球鞋  ");
		super.show();
	}	
}
class LeatherShoes extends Decorator{
	public void show(){
		System.out.print("皮鞋  ");
		super.show();
	}	
}
class Suit extends Decorator{
	public void show(){
		System.out.print("西装  ");
		super.show();
	}	
}
class Tie extends Decorator{
	public void show(){
		System.out.print("领带  ");
		super.show();
	}	
}

public class Test{
	public static void main(String[] args){
		Person person = new Person("kingc");
		System.out.println("第一种装扮");
		Sneakers sk = new Sneakers();
		BigTrouser bt = new BigTrouser();
		Tshirts ts = new Tshirts();
		sk.setComponent(person);
		bt.setComponent(sk);
		ts.setComponent(bt);
		ts.show();
		
		System.out.println("第二种装扮");
		LeatherShoes ls = new LeatherShoes();
		Tie tie = new Tie();
		Suit suit = new Suit();
		ls.setComponent(person);
		tie.setComponent(ls);
		suit.setComponent(tie);
		suit.show();
	}
}


输出:

第一种装扮
T恤  垮裤  破球鞋  装扮的kingc
第二种装扮
西装  领带  皮鞋  装扮的kingc
分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics