工厂模式
设计模式原则:业务和逻辑分离,业务主要表现在主程序中,分离之后,逻辑改变了,业务部分修改的代码要求最小,业务改变了,争取不影响逻辑部分的代码。
1、作用:实例化对象,同时为了增加可扩展性,用户看到的只是接口和抽象类,接口代表的是产品,抽象类是工厂。
2、类图:
3、类图实现
产品:
(1)接口
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
public interface ICar { public void createCar(); }
(2)三个实现类实现结构 top mid low
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
public class LowCar implements ICar { @Override public void createCar() { // TODO Auto-generated method stub System.out.println("low car"); } } public class MidCar implements ICar { @Override public void createCar() { // TODO Auto-generated method stub System.out.println("mid car"); } } public class TopCar implements ICar { @Override public void createCar() { // TODO Auto-generated method stub System.out.println("top car"); } }
(3)抽象工厂 AbstracFactory
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
public abstract class AbstractFactory { public abstract ICar create(); }
(4)三个实现类 继承抽象工厂 top mid low
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
public class LowCarFactory extends AbstractFactory { @Override public ICar create() { // TODO Auto-generated method stub return new LowCar(); } } public class MidCarFactory extends AbstractFactory { @Override public ICar create() { // TODO Auto-generated method stub return new MidCar(); } } public class TopCarFactory extends AbstractFactory { @Override public ICar create() { // TODO Auto-generated method stub return new TopCar(); } }
(5)测试类 分别使用->(实线)只调用接口和抽象类
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
public class User { public static void main(String[] args) { // TODO Auto-generated method stub AbstractFactory factory = new TopCarFactory(); ICar car = factory.create(); car.createCar(); } }