Spring = IOC + AOP
(1), JDK 中 factory 也是比比皆是。
(2), 抽象工厂 -- 换皮肤的软件
抽象产品角色
Moveable
package com.bjsxt.dp.factory; public interface Moveable { void run(); }
具体产品角色 1
Car 实际例子 初衷 :去一个地方让车跑起来。 (只给司机一辆车) 如果让单例 : 那么车的产生过程,不能给司机控制。
package com.bjsxt.dp.factory; import java.util.ArrayList; import java.util.List; public class Car implements Moveable { private static Car car = new Car(); //private static List<Car> cars = new ArrayList<Car>(); public Car() {} public static Car getInstance() { return car; } public void run() { System.out.println("冒着烟奔跑中car......."); } }
具体产品角色 2
Plane
package com.bjsxt.dp.factory; public class Plane implements Moveable { @Override public void run() { System.out.println("扇着翅膀前进中plane...."); } }
抽象工厂
VehicleFactory
package com.bjsxt.dp.factory; public abstract class VehicleFactory { abstract Moveable create(); }
具体工厂
PlaneFactory
package com.bjsxt.dp.factory; public class PlaneFactory extends VehicleFactory { public Moveable create() { return new Plane(); } }
测试类
Test
package com.bjsxt.dp.factory; public class Test { public static void main(String[] args) { //Car c = Car.getInstance(); //Car c2 = Car.getInstance(); //VehicleFactory factory = new BroomFactory(); //Moveable m = factory.create(); //if(c == c2) System.out.println("same car"); //m.run(); } }
- /**
- * 工厂模式的优点在于只要你新增一个产品,只需添加相应产品的工厂,当你需要更换产品时
- * 只需将对应的工厂改变,其它地方不需再改变,当然如果你新增的产品很多,这样容易造成工厂的泛滥
- * 这也是工厂模式的弊端
- */