java工厂模式

package com.test.java;
public class Test {

    public static void getService(ServiceFactory sf){
        Service s = sf.getService();
        s.method1();
        s.method2();
    }
    public static void main(String args[]){
        getService(new impleTation1Factory());
    }
}
interface Service{
    void method1();
    void method2();
}
interface ServiceFactory{
    Service getService();
}
class implementTation1 implements Service{

    public void method1() {
        System.out.println("this is implementTation1 method 1");
    }

    public void method2() {
        System.out.println("this is implementTation1 method 2");
    }
}
class impleTation1Factory implements ServiceFactory{

    public Service getService() {
        return new implementTation1();
    }
    
}

 接口是实现多重继承的途径,而生成遵循某个接口的对象的典型方式就是工厂设计模式。这与直接调用构造器不同,我们可以在工厂对象上调用的是创建方法,而该工厂对象将生成接口的某个实现对象,理论上通过这种方式可以实现接口与实现分离。

posted @ 2013-09-15 19:29  942391815  阅读(115)  评论(0编辑  收藏  举报