工厂模式

  1. 简单工厂

Moveable接口

public interface Moveable {
    void go();
}

Car

public class Car implements  Moveable {

    public void go() {
        System.out.println("Car go wuwuwuwuw....");
    }
}

Plane

public class Plane implements Moveable {
    public void go() {
        System.out.println("plane flying shushua....");
    }
}

可以这样定义CarFactory, 专门生产car的工厂,同样plane也可以定义这样的工厂

public class CarFactory {
    public Moveable create() {
        System.out.println("a car created!");
        return new Car();
    }
}

2.抽象工厂


abstractFactory
public abstract class Food {
   abstract void printName();
}

public abstract class Vehicle { //interface
    abstract void go();
}
public abstract class AbastractFactory {
    abstract Food createFood();
    abstract Vehicle createVehicle();
}

有下列2类产品族:

  • 正常人类
public class Car extends Vehicle{

    public void go() {
        System.out.println("Car go wuwuwuwuw....");
    }
}

public class Bread extends Food{
    public void printName() {
        System.out.println("wdm");
    }
}
  • 魔法人
public class Broom extends Vehicle{
    public void go() {
        System.out.println("Car go wuwuwuwuw....");
    }
}

public class MushRoom extends Food{
    public void printName() {
        System.out.println("dmg");
    }
}

现代工厂负责生产正常人的东西:

public class ModernFactory extends AbastractFactory {
    @Override
    Food createFood() {
        return new Bread();
    }

    @Override
    Vehicle createVehicle() {
        return new Car();
    }

}

魔法工厂生产魔法人的东西:

public class MagicFactory extends AbastractFactory {
    @Override
    Food createFood() {
        return new MushRoom();
    }

    @Override
    Vehicle createVehicle() {
        return new Broom();
    }

}

可以这样去调用:

public class Main {
    public static void main(String[] args) {
       // 要生产其他族的产品,只要换成new MagicFactory();
        AbastractFactory f = new ModernFactory();

        Vehicle c = f.createVehicle();
        c.go();
   
        Food b = f.createFood();
        b.printName();
    }
}

  • 简单工厂:
    在单一的产品维度上扩展性好。比如想要建car,那就建个car工厂,new
    car 就行了。
  • 抽象工厂:
    在整个产品族上扩展性好。只需要建一个另外族的factory,里面写好想生产的系列产品。

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