工厂模式-Factory Pattern

对象创建不要让Client端来做,提供工厂来实现

1. 简单工厂(参数决定类型)

  • 缺点:违反OCP原则,增加新的工程生产对象,则需要修改原来代码
package com.design.pattern.day02;

public class Demo03 {
    public static void main(String[] args) {
        PhoneFactory factory = new PhoneFactory();
        System.out.println(factory.createPhone("huawei").getClass());
        System.out.println(factory.createPhone("apple").getClass());
    }
}

class PhoneFactory {
    //  根据参数类型决定生产的具体是什么类型的对象
    public Phone createPhone(String type) {
        switch (type) {
            case "huawei":
                return new HuaweiPhone();
            case "apple":
                return new ApplePhone();
            default:
                return null;
        }
    }
}

class HuaweiPhone implements Phone {
}

class ApplePhone implements Phone {
}

interface Phone {
}

2. 工厂多方法模式(多方法)

  • 新增新的生产对象时候,只需要添加一个工厂方法即可
  • 符合OCP原则
class PhoneFactory {

    public Phone createApplePhone() {
        return new ApplePhone();
    }

    public Phone createHuaweiPhone() {
        return new HuaweiPhone();
    }
}

3. 静态工厂模式

class PhoneFactory {

    public static Phone createApplePhone() {
        return new ApplePhone();
    }

    public static Phone createHuaweiPhone() {
        return new HuaweiPhone();
    }
}

4. 抽象工厂模式(Abstract Factory Pattern)

  • 工厂勒再去创建一个公共接口
// 工厂类以及工厂的接口
class ToolFactory implements AbstractFactory {

    @Override
    public Animal createAnimal(AnimalNameEnum type) {
        switch (type) {
            case CAT:
                return new Cat();
            case DOG:
                return new Dog();
            default:
                return null;
        }
    }

    @Override
    public Phone createPhone(PhoneNameEnum type) {
        switch (type) {
            case APPLE:
                return new ApplePhone();
            case HUAWEI:
                return new HuaweiPhone();
            default:
                return null;
        }
    }
}

interface AbstractFactory {
    Animal createAnimal(AnimalNameEnum type);

    Phone createPhone(PhoneNameEnum type);
}

// 枚举
enum AnimalNameEnum {
    DOG, CAT
}

enum PhoneNameEnum {
    HUAWEI, APPLE
}

// 动物类型
class Dog implements Animal {
}

class Cat implements Animal {
}

interface Animal {
}

// 手机类型
class HuaweiPhone implements Phone {
}

class ApplePhone implements Phone {
}

interface Phone {
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值