2019-02-15——设计模式 工厂模式

工厂模式分为三种:

1. 简单工厂
特点:一个工厂类根据传入的参量决定创建出那一种产品类的实例,如果想要增加一个产品,需要修改工厂类,该设计破坏了开闭原则。

public interface Fruit {
}

public class Apple implements Fruit {
}

public class Orange implements Fruit {
}

public class SimpleFactory {
    public static Fruit createFruit(String name){
        if("apple".equals(name)){
            return new Apple();
        }else if("orange".equals(name)){
            return new Orange();
        }else{
            throw new RuntimeException("unknown fruit name");
        }
    }
}

public class T {
    public static void main(String[] args) {
        Fruit apple = SimpleFactory.createFruit("apple");
    }
}

2. 工厂方法
特点:定义一个用于创建产品的接口,由子类决定生产什么产品。每个产品都对应了一个创建者,每个创建者独立负责创建对应的产品对象,非常符合单一职责原则。但是每增加一个产品都需要增加一个对应的工厂实现,增加了系统的复杂性

public interface Fruit {
}

public class Apple implements Fruit {
}

public class Orange implements Fruit {
}

public interface FruitFactory {
    Fruit createFruit();
}

public class AppleFactory implements FruitFactory {
    @Override
    public Fruit createFruit() {
        return new Apple();
    }
}

public class OrangeFactory implements FruitFactory {
    @Override
    public Fruit createFruit() {
        return new Orange();
    }
}

public class T {
    public static void main(String[] args) {
        FruitFactory appleFactory = new AppleFactory();
        Fruit apple = appleFactory.createFruit();
        FruitFactory orangeFactory = new OrangeFactory();
        Fruit orange = orangeFactory.createFruit();
    }
}

3. 抽象工厂
特点:提供一个创建产品族的接口,其每个子类可以生产一系列相关的产品。创建相关或依赖对象的家族,而无需明确指定具体类,但是在新增一个产品时,需要修改工厂接口及其子类,破坏了开闭原则

public interface Staple {
}


public class Flour implements Staple {
}


public class Rice implements Staple {
}


public interface Dish {
}


public class Cabbage implements Dish {
}


public class Radish implements Dish{
}


public interface FoodFactory {
    Staple createStaple();
    Dish createDish();
}


public class NorthFood implements FoodFactory {
    @Override
    public Staple createStaple() {
        return new Flour();
    }

    @Override
    public Dish createDish() {
        return new Radish();
    }
}


public class SouthFood implements FoodFactory {
    @Override
    public Staple createStaple() {
        return new Rice();
    }

    @Override
    public Dish createDish() {
        return new Cabbage();
    }
}


public class T {
    public static void main(String[] args) {
        FoodFactory southFoodFactory = new SouthFood();
        Dish cabbage = southFoodFactory.createDish();
        Staple rice = southFoodFactory.createStaple();

        FoodFactory norFoodFactory = new NorthFood();
        Dish rasidh = southFoodFactory.createDish();
        Staple flour = southFoodFactory.createStaple();
    }
}

你可能感兴趣的:(2019-02-15——设计模式 工厂模式)