设计模式-工厂模式

将对象的创建过程,封装到工厂中,不需要使用者来感知。

简单工厂模式: 适用于创建简单的,固定的几种同类型产品。 

角色: 抽象产品、具体产品(多种)、一个创建产品的具体工厂类。

/**
 * 抽象产品-水果
 */
public interface Fruit {
    /**
     * 描述当前水果是什么
     */
    void draw();
}
/**
 * 具体产品-苹果
 */
public class Apple implements Fruit {
    @Override
    public void draw() {
        System.out.println("this is 苹果");
    }
}
/**
 * 具体产品-香蕉
 */
public class Banana implements Fruit {
    @Override
    public void draw() {
        System.out.println("this is 香蕉");
    }
}
/**
 * 创建水果的简单工厂
 */
public class SimpleFactory {
    /**
     * 获取水果
     * @param fruitName
     * @return
     */
    public Fruit getFruit(String fruitName){
        if(null == fruitName){
            return null;
        }
        if(fruitName.equals("apple")){
            return new Apple();
        }else if(fruitName.equals("banana")){
            return new Banana();
        }
        return null;
    }

}

工厂方法模式: 一个工厂创建一种产品,当要增加新的产品时,只需要增加新的工厂,不改变源代码,满足开闭原则。

在简单工厂中,如果有新的水果需要创建,就要去改工厂类中的源代码。 如果一个工厂创建一种水果,有新的水果时,就只需要增加一个新工厂代码就行了。

角色: 抽象产品和具体产品(和上面一样),抽象工厂和具体工厂

/**
 * 抽象工厂
 */
public interface FruitFactory {
    Fruit getFruit();
}
/**
 * 创建苹果的工厂
 */
public class AppleFactory implements FruitFactory {
    @Override
    public Fruit getFruit() {
        return new Apple();
    }
}
/**
 * 创建香蕉的工厂
 */
public class BananaFactory implements FruitFactory {
    @Override
    public Fruit getFruit() {
        return new Banana();
    }
}

上面的例子中,只有一种产品就是水果,如果工厂还需要生产蔬菜呢? 毕竟很多时候需要的东西并不是单一的。

抽象工厂模式: 一个工厂可生产多种不同类型的产品(此例中再增加一种类型产品:蔬菜)

角色: 同工厂方法。 产品增加蔬菜(抽象类和实现类)

增加蔬菜产品:

/**
 * 抽象产品-蔬菜
 */
public interface Vegetables {
    /**
     * 描述当前蔬菜是什么
     */
    void draw();
}
public class Potato implements Vegetables {
    @Override
    public void draw() {
        System.out.println("this is 土豆");
    }
}
public class Tomato implements Vegetables {
    @Override
    public void draw() {
        System.out.println("this is 番茄");
    }
}

改变原有工厂的生产逻辑:

/**
 * 抽象工厂
 */
public interface FruitFactory {
    Fruit getFruit();

    Vegetables getVegetables();   //原来的水果工厂,现在也要生成蔬菜了
}
/**
 * 创建苹果的工厂
 */
public class AppleFactory implements FruitFactory {
    @Override
    public Fruit getFruit() {
        return new Apple();
    }

    @Override
    public Vegetables getVegetables() {
        return new Potato();   //苹果工厂现在要生产土豆了
    }
}
/**
 * 创建香蕉的工厂
 */
public class BananaFactory implements FruitFactory {
    @Override
    public Fruit getFruit() {
        return new Banana();
    }

    @Override
    public Vegetables getVegetables() {
        return new Tomato();   //香蕉工厂现在要生成番茄了
    }
}

抽象工厂,将有关的一组产品,放到同一工厂下生产。

评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值