您的位置:首页 > 编程语言 > Java开发

Java工厂设计模式

2016-04-12 15:10 513 查看
package lu.interfaces;

import static lu.utils.Print.*;

/*工厂方法设计模式

* 在工厂对象上调用的是创建方法,而该工厂对象将生成接口的某个实现的对象。

* 通过这种方式,我们的代码将完全与接口的实现分离,这就使得我们可以透明地将某个实现替换为另一个实现。*/

interface Service{

void method1();

void method2();

}

interface ServiceFactory{

Service getService();

}

class Implementation1 implements Service{

Implementation1(){}

public void method1(){print("Implementation1 method1");}

public void method2(){print("Implementation2 method2");}

}

class Implementation1Factory implements ServiceFactory{

public Service getService(){

return new Implementation1();

}

}

class Implementation2 implements Service{

Implementation2(){}

public void method1(){print("Implementation2 method1");}

public void method2(){print("Implementation2 method2");}

}

class Implementation2Factory implements ServiceFactory{

public Service getService(){

return new Implementation2();

}

}

public class Factory{

public static void serviceConsumer(ServiceFactory fact){

Service s=fact.getService();

s.method1();

s.method2();

}

public static void main(String[] args){

serviceConsumer(new Implementation1Factory());

//Implementations are completely interchangeable;

serviceConsumer(new Implementation2Factory());

}

}

Output

Implementation1 method1

Implementation2 method2

Implementation2 method1

Implementation2 method2
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: