设计模式-----工厂模式

来源:互联网 发布:岗位优化人员优化方案 编辑:程序博客网 时间:2024/05/22 05:32

简单工厂模式
子类不确定需要创建哪个对象的时候,需要利用简单工厂模式,让工厂帮我们生成我们需要的对象

class drinking implements active {    @Override    public void activing() {        System.out.println("drinking...");    }}
class eating implements active {    @Override    public void activing() {        System.out.println("eating...");    }}

工厂方法:

class FactoryMethod {    public active execute(String type) {        if (type.equals("eat")) {            return new eating();        } else if (type.equals("drink")) {            return new drinking();        } else {            System.out.println("请输入正确的类型...");            return null;        }    }}

测试类:

public class Test {    public static void main(String[] args) {        FactoryMethod factory=new FactoryMethod();        active execute = factory.execute("eat");        execute.activing();    }}

创建工厂对象,调用其工厂方法,生成active对象,调用对象的activing方法。

静态工厂方法模式
静态工厂方法模式,将上面的多个工厂方法模式里的方法置为静态的,不需要创建实例,直接调用即可。
工厂方法:

    public class ActiveFactory {          public static active doEat(){              return new eating();          }          public static active doDrink(){              return new drinking();          }      }  

测试类

public class FactoryTest {      public static void main(String[] args) {              Active acive= ActiveFactory.doEat();          acive.activing();      }  }

输出结果:eating…

总结
工厂模式适合:出现了大量的产品需要创建,并且具有共同的接口时,可以通过工厂方法模式进行创建。在上面的模式中,第一种如果传入的字符串有误,不能正确创建对象,所以,大多数情况下,我们会选用第二种——静态工厂方法模式。

0 0