接口:
package com.ajax.pattern.delegate; interface Tool { void work(); }
实现:
package com.ajax.pattern.delegate; public class Broom implements Tool { @Override public void work() { System.out.println("扫把"); } }
package com.ajax.pattern.delegate; public class Mop implements Tool { @Override public void work() { System.out.println("拖把扫地"); } }
被委派者:
package com.ajax.pattern.delegate; import java.util.Calendar; public class Delegate implements Tool { @Override public void work() { Tool p = Calendar.getInstance().get(Calendar.HOUR_OF_DAY) <= 12 ? new Mop() : new Broom(); p.work(); } }
运行:
package com.ajax.pattern.delegate; public class Run { public static void main(String[] args) { new Delegate().work(); } }