9.3 完全解耦
Apply
interface Processor {
String name();
String process(String input);
};
class Upcase implements Processor {
@Override
public String name() {
return getClass().getSimpleName();
}
@Override
public String process(String input) {
return input.toLowerCase();
}
};
class Downcase implements Processor {
@Override
public String name() {
return getClass().getSimpleName();
}
@Override
public String process(String input) {
return input.toUpperCase();
}
};
class Apply {
static void process(Processor processor, String input) {
System.out.println(processor.process(input));
}
public static void chapter9_3() {
String input = "Hyh";
process(new Upcase(), input);
process(new Downcase(), input);
}
};
策略模式:接口定义公共方法,具体子类定义具体实现。其实就是接口的使用。
9.9 接口与工厂
Factories
interface Service {
void method();
};
class Implementation1 implements Service {
@Override
public void method() {
System.out.println("Implementation1 Service!");
}
};
class Implementation2 implements Service {
@Override
public void method() {
System.out.println("Implementation2 Service!");
}
};
interface ServiceFactory {
Service getService();
};
class ImplementationFactory1 implements ServiceFactory {
@Override
public Service getService() {
return new Implementation1();
}
};
class ImplementationFactory2 implements ServiceFactory {
@Override
public Service getService() {
return new Implementation2();
}
};
class Factories {
public static void serviceConsumer(ServiceFactory serviceFactory) {
Service service = serviceFactory.getService();
service.method();
}
public static void chapter9_9() {
serviceConsumer(new ImplementationFactory1());
serviceConsumer(new ImplementationFactory2());
};
};
工厂方法模式:定义一个用于创建对象的接口(ServiceFactory),让子类(Implementation1Factory)决定实例化哪一个类(new Implementation1())。工厂方法使一个类(ServiceFactory)的实例化延迟到子类(Implementation1Factory)。