总述
主要是自己不想做的事交给被委托的对象去做。
类图
委托模式.png实现
调用
package com.company;
public class Main {
public static void main(String[] args) {
// write your code here
Employer employer = new Employer();
employer.printSomething();
}
}
效果
com.company.Employee
Process finished with exit code 0
委托者
package com.company;
public class Employer {
private DelegateInterface contractObject;
public DelegateInterface getContractObject() {
if (this.contractObject == null)this.contractObject = new Employee();
return contractObject;
}
public void printSomething() {
System.out.println(this.getContractObject().exampleMethod());
}
}
被委托者
package com.company;
public class Employee implements DelegateInterface {
@Override
public String exampleMethod() {
return this.getClass().getName();
}
}
双方的契约
package com.company;
public interface DelegateInterface {
String exampleMethod();
}
网友评论