设计模式-工厂方法
1.概念
《设计模式》一书中对于工厂方法模式是这样定义的:定义一个用于创建对象的接口,让子类决定实例化哪一个类。工厂方法使一个类的实例化延迟到其子类。
2.简单工厂模式
先简单说下简单工厂模式,简单工厂模式专门定义一个类来负责创建其他类的实例,被创建的实例通常都具有共同的父类。它又称为静态工厂方法模式。缺点是违反了开闭原则。
Java代码 //生产产品的工厂类 public class ProductFactory{ public static Product generateProduct(int which){ //这个方法是static的 if (which==1) return new ProductA(); else if (which==2) return new ProductB(); } } //抽象产品 public interface Product { ..... } //具体产品A public ProductA implement Product { ProductA () {} } //具体产品B public ProductB implement Product { ProductB () {} } //调用工厂方法 public Client { public method1() { ProductFactory.generateProduct(1); } } Java代码 interface a{} class b implements a{}; class c implements a{}; 工厂类 public class factory{ public static a createa(string name){ class cls=class.forname(name); object obj=cls.getinstance(); return (a)obj; } } //创建实例时 a b=factory.createa("b"); a c=factory.createa("c");
Java代码 //产品 Plant接口 public interface Plant { } //具体产品PlantA,PlantB public class PlantA implements Plant { public PlantA () { System.out.println("create PlantA !"); } public void doSomething() { System.out.println(" PlantA do something ..."); } } public class PlantB implements Plant { public PlantB () { System.out.println("create PlantB !"); } public void doSomething() { System.out.println(" PlantB do something ..."); } } // 抽象工厂方法 public interface AbstractFactory { public Plant createPlant(); } //具体工厂方法 public class FactoryA implements AbstractFactory { public Plant createPlant() { return new PlantA(); } } public class FactoryB implements AbstractFactory { public Plant createPlant() { return new PlantB(); } } //调用工厂方法 public Client { public method1() { AbstractFactory instanceA = new FactoryA(); instanceA.createPlant(); AbstractFactory instanceB = new FactoryB(); instanceB.createPlant(); } }