JAVA装饰者模式简单示例

背景:建立一个工人管理系统,工人的父类下有水管工、木匠等子类,也有A公司工人、B公司工人等子类,装饰者模式就是将工种类型作为参数传到某公司类中,从而简化了所需建立的子类数量。

interface Worker{
	public void doWork();
}

class Plumber implements Worker{
	public void doWork(){
		System.out.println("修水管");
	}
}
class Carpenter implements Worker{
	public void doWork(){
		System.out.println("修门窗");
	}
}

class AWorker implements Worker{
	private Worker worker;
	public AWorker(Worker worker){
		this.worker=worker;
	}
	public void doWork(){
		System.out.println("你好,我是A公司员工");
		worker.doWork();
	}
}

class BWorker implements Worker{
	private Worker worker;
	public BWorker(Worker worker){
		this.worker=worker;
	}
	public void doWork(){
		System.out.println("你好,我是B公司员工");
		worker.doWork();
	}
}


class Test{
	public static void main(String args[]){
		Plumber plumber=new Plumber();
		AWorker aWorker1=new AWorker(plumber);
		aWorker1.doWork();
		
		Carpenter carpenter=new Carpenter();
		BWorker bWorker1=new BWorker(carpenter);
		bWorker1.doWork();
	}
}


执行结果:

你好,我是A公司员工

修水管

你好,我是B公司员工

修门窗

你可能感兴趣的:(编程入门-JAVA)