工厂:简单,工厂,抽象
生成遵循接口的对象,抽象与实现分离,替换新的实现时,不修改代码
package designpattern;
public class FactoryContext {
public static void main(String[] args) {
Service s1 = FactoryContext.getService(new Service1Factory());
s1.update1();
s1.update2();
System.out.println("------------");
Service s2 = FactoryContext.getService(new Service2Factory());
s2.update1();
s2.update2();
}
public static Service getService(ServiceFactory sf) {
return sf.getService();
}
}
interface Service {
void update1();
void update2();
}
interface ServiceFactory {
Service getService();
}
class Service1 implements Service {
@Override
public void update1() {
System.out.println("Service1.update1()");
}
@Override
public void update2() {
System.out.println("Service1.update2()");
}
}
class Service2 implements Service {
@Override
public void update1() {
System.out.println("Service2.update1()");
}
@Override
public void update2() {
System.out.println("Service2.update2()");
}
}
class Service1Factory implements ServiceFactory {
@Override
public Service getService() {
return new Service1();
}
}
class Service2Factory implements ServiceFactory {
@Override
public Service getService() {
return new Service2();
}
}