装饰者模式--穿衣服实例

package com.decorator;

//这是个Componet抽象类
public abstract class Person {
	protected String result;
	public abstract String getCloths();
}
package com.decorator;

//这是一个ConcreteComponet的对象,是Component类的子类
public class Male extends Person{
   
	@Override
	public String getCloths() {
		result = "男性服装搭配:";
		return result;
	}
}

package com.decorator;

//Decator类,负责一组类似功能的装饰
public abstract class Shirt extends Person{
	  public abstract String getCloths();   
}

package com.decorator;

//ConcreteDecator类  是Decator类的子类
public class BigShirt extends Shirt{
    Person person ;
    
    public BigShirt(Person person){
    	this.person = person;
    }
	@Override
	public String getCloths() {
		return person.getCloths() + "大 T-shirt";
	}

}

package com.decorator;

//ConcreteDecator类  是Decator类的子类
public class SmallShirt extends Shirt{
    Person person;
	public SmallShirt(Person person){
		this.person = person;
	}
	@Override
	public String getCloths() {
		String result = person.getCloths() +"小 T-shirt";
		return result;
	}

}

package com.decorator;

//Decator类,负责一组类似功能的装饰
public abstract class Trouser {
	public abstract String getCloths();
}

package com.decorator;

//ConcreteDecator类  是Decator类的子类
public class BigTrouser extends Trouser {
	Person person;

	public BigTrouser(Person person) {
		this.person = person;
	}

	@Override
	public String getCloths() {
		return person.getCloths() + " 大裤";
	}

}

package com.decorator;

public class MainTest {
	public static void main(String agrs[]){
		Person person = new Male();
		//增加一个上衣
		Shirt shirt = new BigShirt(person);
		System.out.println(shirt.getCloths());
		
		//增加一个裤子
		Trouser trouser = new BigTrouser(shirt);
		System.out.println(trouser.getCloths());
	}
}

结果

男性服装搭配:大 T-shirt
男性服装搭配:大 T-shirt 大裤


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