java工厂模式Factory

 工厂模式:

1)我们首先要设计车汽车需要那些流程(face)

package light.zhang.model.model.facotry;

/**
 * 车子建造过程,定义好流程
 * @author witts
 *
 */
public interface ICarface {
    /**
     * 绘制图片
     */
    void drawImage();
    /**
     * 设计模型
     */
    void createModel();
    /**
     * 实现生产
     */
    void implCar();
    /**
     * 测试车子
     */
    void testCar(); 
}

2.汽车生产商(实现)

package light.zhang.model.model.facotry;

/**
 * 奥迪生厂商
 * @author witts
 *
 */
public class AodiCompany  implements ICarface { 
    @Override
    public void drawImage() { 
        System.out.println("奥迪公司-图片模型");
    }

    @Override
    public void createModel() { 
        System.out.println("奥迪公司-创建模型");
    }

    @Override
    public void implCar() {
        System.out.println("奥迪公司-生产车体");
    }

    @Override
    public void testCar() { 
        System.out.println("奥迪公司-测试车体");
    } 
        
}

package light.zhang.model.model.facotry;

/**
 * 宝马公司
 * @author witts
 */
public class BMWCompany implements ICarface {
    @Override
    public void drawImage() {
        System.out.println("宝马公司-图片模型");
    }

    @Override
    public void createModel() {
        System.out.println("宝马公司-创建模型");
    }

    @Override
    public void implCar() {
        System.out.println("宝马公司-生产车体");
    }

    @Override
    public void testCar() {
        System.out.println("宝马公司-测试车体");
    }
 
}

3)4S店现在要整理奥迪宝马的车,4S店就是一个工厂,他负责把奥迪宝马的汽车整理,用户去买车只需要告诉销售员我要买什么车

package light.zhang.model.model.facotry;

/**
 * 4S店开始整理要销售那些车?
 * @author witts
 *
 */
public class Car4SDianFactory {
    
    public ICarface getCar(int type) {
         if(type == 1) {
             return new AodiCompany();
         }
         if(type == 2) {
             return new BMWCompany();
         }
         return null;
    }
}

4)用户开始买车(调用)

package light.zhang.model.model.facotry;

/**
 * 用户开始去4S店买车
 * @author witts
 *
 */
public class UserShoppingCar {
    
    public static void main(String[] args) {
        Car4SDianFactory factory=new Car4SDianFactory();
        ICarface aodiCar=factory.getCar(1);//奥迪公司的汽车
        aodiCar.testCar();
        
        ICarface bmwCar =  factory.getCar(2);//宝马公司的汽车
        bmwCar.testCar();
    }
}
原文地址:https://www.cnblogs.com/light-zhang/p/8384302.html