本文是在学习中的总结,欢迎转载但请注明出处:http://blog.csdn.net/pistolove/article/details/46402017
工厂方法模式:定义了一个创建对象的接口,但由子类来决定要实例化的的类是哪一个。
工厂方法让类把实例化推迟到子类中。
减少了应用程序和具体类之间的依赖进行松耦合。
OO原则:依赖抽象,不要依赖具体类
通过以下代码对简单工厂模式进行理解:
抽象产品角色:
package com.design.factoryMethod; //抽象产品角色 public abstract class Car { public String carname; public void run(String voice){ System.err.println("run fast " + voice); } public void say(){ System.err.println("create "+carname+" success"); } }
//具体产品角色
package com.design.factoryMethod; public class Benchi extends Car { public Benchi(){ carname = "Benchi"; } }
package com.design.factoryMethod; public class Biyadi extends Car{ public Biyadi(){ carname = "Biyadi"; } }
抽象工厂:
package com.design.factoryMethod; public abstract class Create { //让子类决定生产什么产品 public Car factoryMethod(String name){ Car car = createCar(name); //go car.run("120"); return car; } public abstract Car createCar(String name); }
具体工厂:
package com.design.factoryMethod; public class CarCreate extends Create { @Override public Car createCar(String name) { Car car = null; try { car = (Car) Class.forName("com.design.factoryMethod."+name).newInstance(); } catch (Exception e) { } return car; } }
客户端测试:
package com.design.factoryMethod; public class Test { public static void main(String[] args) { Create create = new CarCreate(); Car car = create.factoryMethod("Biyadi"); car.say(); Create create2 = new CarCreate(); Car car2 = create2.factoryMethod("Benchi"); car2.say(); } }
测试结果:
run fast 120
create Biyadi success
run fast 120
create Benchi success
时间: 2024-11-05 22:05:37