The factory pattern of java design pattern (factory method/abstract factory) (2)

In this human world, there are some roads that have to be faced alone, and travel alone. No matter how long and long the road, no matter how dark or dark the night is, you have to walk silently.

Design pattern learning, I will blog about 23 design patterns in the near future , so stay tuned~

What is the factory model?

The factory pattern belongs to the creation type in the design pattern. We do not expose the specific logic of creating the object, but encapsulate the logic in a method, then this method can be regarded as a factory.

Baidu Encyclopedia

Advantages and disadvantages of the factory model

advantage

  • The specific code logic implementation is not exposed, the code logic is encapsulated in a method, no need to care about the code details (the details refer to the code implementation logic) can be directly called to achieve the effect, easy to use
  • The implementer and the caller are completely decoupled and comply with the principle of dependency inversion (interface-oriented programming)
  • Realize the development of extensions, close the modification, and observe the principle of opening and closing

Disadvantages:

  • If you add a module, the code changes are relatively large
  • A lot of factory (Foatory) classes need to be created, which increases code abstraction and difficulty in understanding

Factory pattern classification

  • Simple factory pattern
  • Factory method pattern
  • Abstract factory pattern

Why learn the factory model? What is the usage scenario?

To learn anything, we should first consider why we should learn from him and what benefits will be brought to us by learning from him. For the short answer factory model , let’s give you an example,

Assumption: I want to buy a car, what should I do?

  • Go to the place where the car is sold, first pick a car you like;
    (the place where the car is sold is equivalent to a factory)
  • Then process the car ;
    processing the car is equivalent to writing the details of the car
  • Pay the money and pick up the car;
    pay the money and pick up the car, which is equivalent to the object of the factory bar car. Return it to me

It can be seen that this is a simple factory model. I pay and you give me the car instead of me directly building the car.

What are the disadvantages of not writing the factory model:

  假设我很有钱,一天买一辆车,不同品牌不同型号,那就买一次车得创建一次车的细节,从刚
开始画车的轮廓,到最后给车上色,都由我一个人单独完成,

Advantages of the factory model:

我出钱,你给我车,细节我不用管.就是这么简单

(Of course this is just an example, the code of the car must be written by you, just to say that there will be a lot of the same code)

This is the simple factory model~

Ordinary factory model

public abstract class OrdinaryCar {
    
    
    //汽车名字
    public abstract void CarName();
}

//五菱汽车
public class OrdinaryWuLin extends OrdinaryCar {
    
    
    @Override
    public void CarName() {
    
    
        Log.i("Factory:简单工厂之:","五菱宏光");
    }
}

//大众汽车
public class OrdinaryDaZhong extends OrdinaryCar {
    
    
    @Override
    public void CarName() {
    
    
        Log.i("Factory:简单工厂之:","大众汽车");
    }
}

//简单工厂实现
public class OrdinaryFactory {
    
    
    public static OrdinaryCar OrdinaryCar(String carName){
    
    
        if ( carName.equals("WuLing")) {
    
    
            //返回五菱
            return  new OrdinaryWuLin();
        }else if(carName.equals("DaZhong")){
    
    
            //返回大众
            return new OrdinaryDaZhong();
        }else {
    
    
            return null;
        }
    }
}

Code usage:

OrdinaryCar ordinaryWuLin1 = OrdinaryFactory.OrdinaryCar("WuLing");
OrdinaryCar ordinaryDaZhong1 = OrdinaryFactory.OrdinaryCar("DaZhong");
ordinaryWuLin1.CarName();//五菱汽车
ordinaryDaZhong1.CarName();//大众汽车

advantage:

  • Simple to use, no difficult logic

Disadvantages:

UML类图(2.1):


UML class diagram code:

UML class diagram reference documentation , if you really don't want to learn this UML class diagram, just skip this paragraph.

@startuml
abstract OrdinaryCar{
    
    
    abstract CarName();
}
OrdinaryDaZhong ..|> OrdinaryCar

OrdinaryWuLing ..|> OrdinaryCar

OrdinaryFactory ->OrdinaryDaZhong

OrdinaryFactory ->OrdinaryWuLing

消费者 -> OrdinaryFactory

class 消费者
note bottom :只与OrdinaryFactory交互,不管如何创建车\n我只给你车的类型,你给我返回车

@enduml

简单工厂Log结果图(3.1):

Factory method pattern

Factory method ideas:

  • A car factory (Factory) meets the creation of a car, and then the main factory manages the car factory

The simple understanding is that the main factory manages every car factory, and the car factory manages the creation of each car. Now I want to buy a car with the model of Wuling Hongguang A3. I give the main factory money, and the main factory goes to Wuling Hongguang Factory, Wuling Hongguang was looking for A series cars and finally gave me the corresponding car

//购买车的名字
public abstract class FaCar {
    
    
    public abstract void CarName();
}
//汽车总工厂
public interface FaFactory {
    
    
    FaCar createCar();
}

//大众汽车
public class FaDaZhong extends FaCar {
    
    
    @Override
    public void CarName() {
    
    
        Log.i("Factory:工厂方法之:","大众汽车");
    }
}

//大众汽车工厂类
public class FaDaZhongFactory implements FaFactory{
    
    
    @Override
    public FaCar createCar() {
    
    
        return new FaDaZhong();
    }
}

advantage:

Disadvantages:

  • Because a class creates a factory, it will increase the code, which is not conducive to management

If I want to add Wuling and Tesla now, how to increase:

//五菱汽车
public class FaWuLing extends FaCar{
    
    
    @Override
    public void CarName() {
    
    
        Log.i("Factory:工厂方法之:","五菱汽车");
    }
}

//五菱工厂
public class FaWuLingFactory implements FaFactory{
    
    
    @Override
    public FaCar createCar() {
    
    
        return new FaWuLing();
    }
}

//特斯拉汽车
public class FaTeSiLa extends FaCar {
    
    
    @Override
    public void CarName() {
    
    
        Log.i("Factory:工厂方法之:","特斯拉汽车");
    }
}

//特斯拉工厂
public class FaTeSiLaFactory implements FaFactory{
    
    
    @Override
    public FaCar createCar() {
    
    
        return new FaTeSiLa();
    }
}

Code usage:

FaCar faDaZhong = new FaDaZhongFactory().createCar();
FaCar faWuLing = new FaWuLingFactory().createCar();
FaCar faTeSiLa = new FaTeSiLaFactory().createCar();
faDaZhong.CarName();//大众汽车
faWuLing.CarName();//五菱汽车
faTeSiLa.CarName();//特斯拉汽车 

工厂方法模式Log图(3.2):


UML类图(2.2):


UML class diagram code:

UML class diagram reference documentation , if you really don't want to learn this UML class diagram, just skip this paragraph.

@startuml
interface FaFactory{
    
    
   Car createCar();
}
note right:用来创建车类型

abstract class FaCar {
    
    
         abstract void CarName();
}
note left:用来创建车名字

FaDaZhong ..|> FaCar
FaWuLing ..|> FaCar
FaTeSiLa ..|> FaCar

FaCarDaZhongFactory --|> FaFactory
FaWuLingFactory --|> FaFactory
FaTeSiLaFactory --|> FaFactory


class FaCarDaZhongFactory{
    
    
     returtn FaDaZhong()
}
class FaWuLingFactory{
    
    
     returtn FaWuLing()
}
class FaTeSiLaFactory{
    
    
     returtn FaTeSiLa()
}
@enduml

Abstract factory pattern

What is the abstract factory pattern:

For example, Huawei and Xiaomi;

Compared with mobile phones, Xiaomi mobile phones and Huawei mobile phones belong to the mobile phone series(参考图1.1)

(参考图1.1):

Compared with Huawei, Huawei mobile phones and Huawei computers belong to the Huawei series.参考图(1.2)

参考图(1.2):


If I am in a Suning physical store, I want to buy a Xiaomi phone first, do I go to the Xiaomi store first, and then find the Xiaomi phone series, if I want to buy a Xiaomi computer, find the Xiaomi computer series, and buy the Xiaomi computer again

Here, the Suning physical store acts as the factory category.
Go to the Suning physical store to find the Xiaomi store. The Xiaomi store acts as the Xiaomi factory.
Then the Xiaomi store gives you the Xiaomi mobile phone/Xiaomi computer, which acts as the specific Xiaomi mobile phone. Realize
Huawei is the same, first go to the main factory (Suning physical store), then go to the Huawei store (Huawei Factory)
to find what you want to buy

I don't know if I explain this way, you can understand it, please follow my footsteps to realize it bit by bit~

I feel that the abstract factory class is a bit of a " mock doll" meaning<(  ̄▽ ̄ )/

Code:

Define 2 interfaces : used to implement the specific details of mobile phones and computers, such as mobile phones can be opened, computers can learn, etc.

//手机细节实现
public interface IPhone {
    
    
    // 打开手机
    void open();
    //连接Wifi
    void wifi();
     // 发送短信
    void sendSMS();
}

//电脑细节实现
public interface IComputer {
    
    
    //学习
    void study();
	 //玩耍
    void play();
     //看电视
    void WatchTv();
}

Create Huawei mobile phone, Xiaomi mobile phone, Huawei computer, Xiaomi computer:

//华为手机
public class HuaWeiPhone implements IPhone{
    
    
    @Override
    public void open() {
    
    
        Log.i("Factory抽象工厂方法:","华为手机打开");
    }
    @Override
    public void wifi() {
    
    
        Log.i("Factory抽象工厂方法:","华为手机WIFI打开");
    }
    @Override
    public void sendSMS() {
    
    
        Log.i("Factory抽象工厂方法:","华为手机发送消息");
    }
}

//华为电脑
public class HuaWeiComputer implements IComputer{
    
    
    @Override
    public void study() {
    
    
        Log.i("Factory抽象工厂方法:","华为电脑学习");
    }
    @Override
    public void play() {
    
    
        Log.i("Factory抽象工厂方法:","华为电脑玩耍");
    }
    @Override
    public void WatchTv() {
    
    
        Log.i("Factory抽象工厂方法:","华为电脑看电视");
    }
}

//小米手机
public class XiaoMiPhone implements IPhone{
    
    
    @Override
    public void open() {
    
    
        Log.i("Factory抽象工厂方法:","小米手机打开");
    }
    @Override
    public void wifi() {
    
    
        Log.i("Factory抽象工厂方法:","小米手机WIFI打开");
    }
    @Override
    public void sendSMS() {
    
    
        Log.i("Factory抽象工厂方法:","小米手机发送消息");
    }
}

//小米电脑:
public class XiaoMiComputer implements IComputer{
    
    
    @Override
    public void study() {
    
    
        Log.i("Factory抽象工厂方法:","小米电脑学习");
    }
    @Override
    public void play() {
    
    
        Log.i("Factory抽象工厂方法:","小米电脑玩耍");
    }
    @Override
    public void WatchTv() {
    
    
        Log.i("Factory抽象工厂方法:","小米电脑看电视");
    }
}

Create a general factory, used to return to Xiaomi factory, or Huawei factory

public interface TotalFactory {
    
    
    /**
     * 创建手机系列
     */
    IPhone createPhone();

    /**
     * 创建电脑系列
     */
    IComputer createComputer();
}

Create a Huawei factory and create a Xiaomi factory; used to process corresponding products

//华为工厂
public  class HuaWeiFactory implements TotalFactory {
    
    
    @Override
    public IPhone createPhone() {
    
    
        return new HuaWeiPhone();
    }
    @Override
    public IComputer createComputer() {
    
    
        return new HuaWeiComputer();
    }
}

//小米工厂
public  class XiaoMiFactory implements TotalFactory {
    
    
    @Override
    public IPhone createPhone() {
    
    
        return new XiaoMiPhone();
    }
    @Override
    public IComputer createComputer() {
    
    
        return new XiaoMiComputer();
    }
}

Use code:

XiaoMiFactory xiaoMiFactory = new XiaoMiFactory();
IComputer computer = xiaoMiFactory.createComputer();
IPhone phone = xiaoMiFactory.createPhone();
computer.play();//小米电脑
computer.study();//小米电脑
computer.WatchTv();//小米电脑

phone.open();//小米手机
phone.sendSMS();//小米手机
phone.wifi();//小米手机

抽象工厂模式Log图(3.3):


UML类图(2.3):

Just take the Huawei series as an example (too many and too messy are more confused)


advantage:

  • We only interact with the total factory (TotalFactory), you need a Xiaomi mobile phone to new Xiaomi factory, and then create the corresponding method Xiaomi mobile phone.
  • Comply with the opening and closing principle (open for extension, closed for modification)
  • Comply with the principle of dependency inversion (interface-oriented programming)

Note:
I am using the Android project. Those who have never learned Android can download the code directly. You can download the project and you are running~

Complete code

Recent articles:

Singleton pattern of java design pattern (1)

Prototype pattern of java design pattern (3)

The builder pattern of java design pattern (4)

Adapter pattern of java design pattern (5)

Go to the design pattern/design principle catalog page

The original is not easy, remember to like it~ I will update all 23 articles as much as possible in the near future. If you want to learn design patterns, remember to pay attention (#^.^#)

Guess you like

Origin blog.csdn.net/weixin_44819566/article/details/112307879