java 工厂模式

不使用模式:

/**
 * Created by Torres on 17/2/21.
 *
 */
class BWMCar {
    public BWMCar() {
        System.out.println("生产一辆BWM");
    }
}

class AUDICar {
    public AUDICar() {
        System.out.println("生产一辆Audi");
    }
}

public class Client1 {
    public static void main(String[] args) {
        BWMCar bwmCar = new BWMCar();
        AUDICar audiCar = new AUDICar();
    }
}

简单工厂模式

package FactoryPattern;

/**
 * Created by Torres on 17/2/21.
 * 简单工厂
 */
abstract class Car {
    public Car() {
    }
}

class Audi extends Car {
    public Audi() {
        System.out.println("生产一辆Audi");
    }
}

class Bmw extends Car {
    public Bmw() {
        System.out.println("生产一辆bmw");
    }
}

class Factory {
    public Car createCar(String type) {
        switch (type) {
            case "audi":
                return new Audi();
            case "bmw":
                return new Bmw();
            default:
                break;
        }
        return null;
    }
}
public class Client2 {
    public static void main(String[] args) {
        Factory factory = new Factory();
        factory.createCar("audi");
        factory.createCar("bmw");
    }
}

工厂方法模式

package FactoryPattern;

/**
 * Created by Torres on 17/2/21.
 */

interface CarFactory {
    Car createCar();
}

class AudiFactory implements CarFactory {

    @Override
    public Car createCar() {
        return new Audi();
    }
}

class BwmFactory implements CarFactory {

    @Override
    public Car createCar() {
        return new Bmw();
    }
}

public class Client3 {
    public static void main(String[] args) {
        CarFactory bwmFactory = new BwmFactory();
        bwmFactory.createCar();
        CarFactory audifactory = new AudiFactory();
        audifactory.createCar();

    }
}

你可能感兴趣的:(java 工厂模式)