工厂设计模式

来源:互联网 发布:2017广电禁止网络电视 编辑:程序博客网 时间:2024/05/29 18:46
package interfaces;


/**
 * 工厂设计模式
 * */
interface Service{
void method1();
void method2();
}
interface ServiceFactory{
Service getService();
}
class Implementation1 implements Service{
Implementation1(){}
public void method1(){System.out.println("Implementation1 method1");}
public void method2(){System.out.println("Implementation1 method2");}
}
class Implementation1Factory implements ServiceFactory{
public Service getService(){return new Implementation1();}
}
class Implementation2 implements Service{
Implementation2(){}
public void method1(){System.out.println("Implementation2 method1");}
public void method2(){System.out.println("Implementation2 method2");}
}
class Implementation2Factory implements ServiceFactory{
public Service getService(){return new Implementation2();}
}
public class Factories {
public static void serviceConsumer(ServiceFactory fact){
Service  s = fact.getService();
s.method1();
s.method2();
}
public static void main(String[] args){
serviceConsumer(new Implementation1Factory());
serviceConsumer(new Implementation2Factory());
}

}


输出结果:

Implementation1 method1
Implementation1 method2
Implementation2 method1
Implementation2 method2

原创粉丝点击