世界上并没有完美的程序,但是我们并不因此而沮丧,因为写程序就是一个不断追求完美的过程。
- 意图
表示层与业务层的解耦 - 类图
- 实例
interface BusinessService {
/**
* 执行
*/
void doProcession ();
}
static class AService implements BusinessService {
@Override
public void doProcession() {
System.out.println("AService::doProcession");
}
}
static class BService implements BusinessService {
@Override
public void doProcession() {
System.out.println("BService::doProcession");
}
}
/**
* 以上可以看做是业务工场
*/
static class BusinessFactory {
public BusinessService getBusinessService (String type) {
if ("A".equals(type)) {
return new AService();
} else {
return new BService();
}
}
}
static class BusinessDelegate {
private BusinessFactory businessFactory = new BusinessFactory();
private String type;
public void setType(String type) {
this.type = type;
}
public void doTask () {
BusinessService service = businessFactory.getBusinessService(type);
service.doProcession();
}
}
static class Client {
private BusinessDelegate businessDelegate;
public Client (BusinessDelegate businessDelegate) {
this.businessDelegate = businessDelegate;
}
public void doTask () {
businessDelegate.doTask();
}
}
- 测试
public static void main(String[] args) {
BusinessDelegate businessDelegate = new BusinessDelegate();
businessDelegate.setType("A");
Client client = new Client(businessDelegate);
client.doTask();
businessDelegate.setType("B");
client.doTask();
}
运行结果:
AService::doProcession
BService::doProcession