工厂模式-打工人必学的设计模式

工厂模式

用来封装和管理类的创建,对于类创建步骤比较复杂的代码,使用工厂模式简化创建。

简单工厂


分为三步:

  1. 创建手机接口
  2. 实现具体的手机类
  3. 实现工厂类
public interface Phone{
    void call();
}
public class IPhone implements Phone{
    public void call(){
        System.out.println("苹果手机");
    }
}

public class HuaweiPhone implements Phone{
    public void call(){
        System.out.println("华为手机");
    }
}
public class PhoneFactory{
    public Phone create(String brand){
        Phone phone=null;
        Switvh(brand){
            case "iphone":
                phone=new IPhone();
                break;
            case "huawei":
                phone=new HuaweiPhone();
                break;
            default:
                break;
        }
        return phone;
    }
}

弊端:新加一个小米手机会修改工厂类的switch方法,这就违背了开闭原则。

工厂方法

public interface Phone{
    void call();
}

public class IPhone implements Phone{
    public void call(){
        System.out.println("苹果手机");
    }
}

public class HuaweiPhone implements Phone{
    public void call(){
        System.out.println("华为手机");
    }
}
public abstract class Factory{
    Phone createPhone();
}

public class IPhoneFactory extends Factory{
    public Phone createPhone(){
        return new IPhone();
    }
}

public class HuaWeiPhoneFactory extends Factory{
    public Phone createPhone(){
        return new HuaweiPhone();
    }
}

如果新加入一个三星手机,那么我们需要做什么?

  1. 创建三星手机类
public class SamsungPhone implements Phone{
    public void call(){
        System.out.println("三星手机");
    }
}
  1. 创建三星手机工厂
public class SamsungPhoneFactory extends Factory{
    public Phone createPhone(){
        return new SamsungPhone();
    }
}

使用

public static void mian(String[] args){
  Phone samsung=SamsungPhoneFactory.createPhone();
  samsung.call();
}

简单工厂与工厂方法对比:

工厂方法把工厂类进行了抽象化,假如果新加入一个手机,那么只需要实现一个小米手机类与小米手机工厂类,解决了开闭原则。

抽象工厂模式

public interface Phone{
    void call();
}

public class IPhone implements Phone{
    public void call(){
        System.out.println("苹果手机");
    }
}

public class HuaweiPhone implements Phone{
    public void call(){
        System.out.println("华为手机");
    }
}
public interface Pad{
    void call();
}

public class IPad implements Pad{
    public void call(){
        System.out.println("苹果平板");
    }
}

public class HuaweiPad implements Pad{
    public void call(){
        System.out.println("华为平板");
    }
}
public abstract class Factory{
    Phone createPhone();
    Pad createPad();
    
}

public class AppleFactory extends Factory{
    public Phone createPhone(){
        return new IPhone();
    }
    public Pad createPad(){
        return new IPad();
    }
}

public class HuaWeiFactory extends Factory{
    public Phone createPhone(){
        return new HuaweiPhone();
    }
    public Pad createPad(){
        return new HuaWeiPad();
    }
}

如何抉择?

如果产品结构单一,那么可以选择工厂模式,如果产品结构不单一,那么选择抽象工厂模式

posted @ 2023-01-04 16:10  帅气的涛啊  阅读(22)  评论(0编辑  收藏  举报