Mars老师讲解的装饰者模式代码例子


Worker.java

package com.worker;

public interface Worker {
	public void doSomeWork();
}

Carpenter.java

package com.worker;

public class Carpenter implements Worker{
	@Override
	public void doSomeWork() {
		System.out.println("小木匠,修理门窗");
	}
}


Plumber.java

package com.worker;

public class Plumber implements Worker{

	@Override
	public void doSomeWork() {
		System.out.println("水管工,修水管。");	
	}
}


AWorker.java

package com.worker;

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


Test.java

package com.worker;

public class Test {
	public static void main(String [] args){
		Carpenter carpenter = new Carpenter();
		carpenter.doSomeWork();
		
		Plumber plumber = new Plumber();
		plumber.doSomeWork();
		
		AWorker aworker = new AWorker(carpenter);
		aworker.doSomeWork();
	}
}






你可能感兴趣的:(java)