Java Design pattern factory pattern: Factory Method/Abstract Factory ②

  • What is the factory model?
  • Advantages and disadvantages of the Factory model
  • Factory mode classification
  • Why learn the factory model? What are the usage scenarios?
  • Common Factory model
  • Factory method pattern
  • Abstract Factory pattern

In this world, some roads must be faced and trudge alone. No matter how long and far the road is, no matter how dark and dark the night is, you must walk alone and silently.

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

What is the factory model?

The factory pattern is the creation type of the design pattern, where we do not expose the concrete logic for creating objects, but encapsulate the logic in a method that can be considered a factory.

Baidu encyclopedia

Advantages and disadvantages of the Factory model

advantages

  • Do not expose the specific code logic implementation, the code logic encapsulated in a method, do not care about the code details (details refer to the code implementation logic) directly call to achieve the effect, easy to use
  • Implementor and caller are completely decoupled, following the dependency inversion principle (interface oriented programming)
  • The realization of the expansion of the development, to modify the closed, comply with the open and closed principle

Disadvantages:

  • Adding a module to the code changes a lot
  • Many factory (Foatory) classes need to be created, which increases code abstraction and difficulty to understand

Factory mode classification

  • Simple Factory model
  • Factory method pattern
  • Abstract Factory pattern

Why learn the factory model? What are the usage scenarios?

To learn anything, we should first consider why we should learn from him and what benefits he will bring us. To give you an example of the short answer factory model,

Suppose: I am buying a car, what should I do?

  • Go to a car store and pick out a car you like. (The place that sells cars is like a factory.)
  • Then the car is processed; Working on the car is like writing about the details of the car
  • Pay to pick up the car; Paying to pick up the car is the factory equivalent of returning the object of the car to me

As you can see, it’s a simple factory model, I pay, you give me the car, instead of me building the car,

What are the disadvantages of not writing factory mode:

Let's say I have a lot of money, and I buy a car every day, and I have to create the details of the car, from the outline of the car to the color of the car, all by myself.Copy the code

Advantages of the factory model:

I'll pay, you give me the car, I don't worry about the details. It's that simpleCopy the code

(Of course this is just an example, the vehicle code must be written by us, just to say there will be much less of the same code)

This is the simple factory pattern

Common Factory model

public abstract class OrdinaryCar {
    // The name of the car
    public abstract void CarName(a);
}

// Wuling Automobile
public class OrdinaryWuLin extends OrdinaryCar {
    @Override
    public void CarName(a) {
        Log.i("Factory: simple Factory:".Wuling Hongguang); }}// Volkswagen
public class OrdinaryDaZhong extends OrdinaryCar {
    @Override
    public void CarName(a) {
        Log.i("Factory: simple Factory:"."Volkswagen"); }}// Simple factory implementation
public class OrdinaryFactory {
    public static OrdinaryCar OrdinaryCar(String carName){
        if ( carName.equals("WuLing")) {
            // Return to Wuling
            return  new OrdinaryWuLin();
        }else if(carName.equals("DaZhong")) {// Return to public
            return new OrdinaryDaZhong();
        }else {
            return null; }}}Copy the code

Code use:

OrdinaryCar ordinaryWuLin1 = OrdinaryFactory.OrdinaryCar("WuLing");
OrdinaryCar ordinaryDaZhong1 = OrdinaryFactory.OrdinaryCar("DaZhong");
ordinaryWuLin1.CarName();// Wuling Automobile
ordinaryDaZhong1.CarName();// Volkswagen
Copy the code

Advantages:

  • Simple to use, no hard logic

Disadvantages:

  • Violate OCP(open and closed) principles (extend development, modify closed)
  • Code is prone to errors, too many if and else judgments

UML class diagrams (2.1) :

\

UML class diagram code:

UML class diagram reference documentation, if you really don’t want to learn the UML class diagram, just skip this section.

@startuml
abstract OrdinaryCar{
    abstract CarName(a); } OrdinaryDaZhong .. |> OrdinaryCar OrdinaryWuLing .. | > OrdinaryCar OrdinaryFactory - > OrdinaryDaZhong OrdinaryFactory - > OrdinaryWuLing consumers - > OrdinaryFactoryclassconsumersnote bottom: only withOrdinaryFactoryInteractive, however create car \nI only give you the type of car, you give me back the car @enduml
Copy the code

Simple factory Log result diagram (3.1):

Factory method pattern

Factory method thought:

  • A Factory satisfies the creation of a vehicle, which is then managed by the master Factory

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

// The name of the car to purchase
public abstract class FaCar {
    public abstract void CarName(a);
}
// The car factory
public interface FaFactory {
    FaCar createCar(a);
}

// Volkswagen
public class FaDaZhong extends FaCar {
    @Override
    public void CarName(a) {
        Log.i("Factory: Method of Factory:"."Volkswagen"); }}// Volkswagen factory
public class FaDaZhongFactory implements FaFactory{
    @Override
    public FaCar createCar(a) {
        return newFaDaZhong(); }}Copy the code

Advantages:

  • Meets the open closed principle (open for extensions, closed for modifications)
  • It’s easier to use, but there’s a lot more code

Disadvantages:

  • Because one class creates a factory, the code becomes too much to manage

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

// Wuling Automobile
public class FaWuLing extends FaCar{
    @Override
    public void CarName(a) {
        Log.i("Factory: Method of Factory:".Wuling Automobile); }}// Wuling Factory
public class FaWuLingFactory implements FaFactory{
    @Override
    public FaCar createCar(a) {
        return newFaWuLing(); }}// Tesla Motors
public class FaTeSiLa extends FaCar {
    @Override
    public void CarName(a) {
        Log.i("Factory: Method of Factory:"."Tesla Motors"); }}// Tesla factory
public class FaTeSiLaFactory implements FaFactory{
    @Override
    public FaCar createCar(a) {
        return newFaTeSiLa(); }}Copy the code

Code use:

FaCar faDaZhong = new FaDaZhongFactory().createCar();
FaCar faWuLing = new FaWuLingFactory().createCar();
FaCar faTeSiLa = new FaTeSiLaFactory().createCar();
faDaZhong.CarName();// Volkswagen
faWuLing.CarName();// Wuling Automobile
faTeSiLa.CarName();// Tesla Motors
Copy the code

Factory method mode Log diagram (3.2):

\

UML class diagrams (2.2) :

\

UML class diagram code:

UML class diagram reference documentation, if you really don’t want to learn the UML class diagram, just skip this section.

@startuml
interface FaFactory{
   Car createCar(a); } note right: used to create the car typeabstract class FaCar {
         abstract void CarName(a); } note left: create vehicle name FaDaZhong.. |> FaCar FaWuLing .. |> FaCar FaTeSiLa .. |> FaCar FaCarDaZhongFactory --|> FaFactory FaWuLingFactory --|> FaFactory FaTeSiLaFactory --|> FaFactoryclass FaCarDaZhongFactory{
     returtn FaDaZhong(a)
}
class FaWuLingFactory{
     returtn FaWuLing(a)
}
class FaTeSiLaFactory{
     returtn FaTeSiLa(a)
}
@enduml
Copy the code

Abstract Factory pattern

What is the Abstract Factory pattern:

Huawei and Xiaomi;

Compared with mobile phones, Xiaomi phones and Huawei phones belong to mobile phone series (see Figure 1.1).

(Refer to Figure 1.1):

Compared with Huawei, Huawei mobile phones and Huawei computers belong to huawei series (1.2)

Refer to figure (1.2) :



If I now suning entity shop, I want to buy millet mobile phone first, I am not to go to millet shop first, then find millet mobile phone series, if want to buy millet computer, find millet computer series, buy millet computer again \

Here, The Suning physical store serves as the general Factory. Go to the Suning physical store and find the Mi store, which serves as the Mi Factory. Then the Mi store gives you mi mobile phone/MI computer. As the concrete realization of Xiaomi xiaomi mobile phone, Huawei is the same, first go to the main Factory (Suning physical store), and then go to huawei Factory store (Huawei Factory) to find what you want to buy

I don’t know if you can understand me by my explanation. Please follow my steps step by step to achieve ~

Feel abstract factory class is a bit ‘nesting baby’ meaning <( ̄▽ ̄)/

Code implementation:

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

// The phone details are implemented
public interface IPhone {
    // Turn on your cell phone
    void open(a);
    / / Wifi connection
    void wifi(a);
     // Send SMS messages
    void sendSMS(a);
}

// Computer details are implemented
public interface IComputer {
    / / learning
    void study(a);
	 / / play
    void play(a);
     / / watching TV
    void WatchTv(a);
}
Copy the code

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

// Huawei phone
public class HuaWeiPhone implements IPhone{
    @Override
    public void open(a) {
        Log.i("Factory Abstract Factory method :"."Huawei Phone on");
    }
    @Override
    public void wifi(a) {
        Log.i("Factory Abstract Factory method :"."Huawei Phone WIFI turned on");
    }
    @Override
    public void sendSMS(a) {
        Log.i("Factory Abstract Factory method :"."Huawei phones send messages."); }}// Huawei Computer
public class HuaWeiComputer implements IComputer{
    @Override
    public void study(a) {
        Log.i("Factory Abstract Factory method :"."Huawei Computer Learning");
    }
    @Override
    public void play(a) {
        Log.i("Factory Abstract Factory method :"."Huawei Computer Play");
    }
    @Override
    public void WatchTv(a) {
        Log.i("Factory Abstract Factory method :"."Huawei computer watching TV"); }}// Xiaomi phone
public class XiaoMiPhone implements IPhone{
    @Override
    public void open(a) {
        Log.i("Factory Abstract Factory method :"."Xiaomi phone open");
    }
    @Override
    public void wifi(a) {
        Log.i("Factory Abstract Factory method :"."Mi Phone WIFI turned on");
    }
    @Override
    public void sendSMS(a) {
        Log.i("Factory Abstract Factory method :"."Xiaomi phones send messages."); }}// Xiaomi computer:
public class XiaoMiComputer implements IComputer{
    @Override
    public void study(a) {
        Log.i("Factory Abstract Factory method :"."Xiaomi Computer Learning");
    }
    @Override
    public void play(a) {
        Log.i("Factory Abstract Factory method :"."Xiaomi Computer Play");
    }
    @Override
    public void WatchTv(a) {
        Log.i("Factory Abstract Factory method :"."Xiaomi computer watching TV"); }}Copy the code

Create a master factory to return to xiaomi factory or Huawei factory

public interface TotalFactory {
    /** * Create mobile phone series */
    IPhone createPhone(a);

    /** * create computer series */
    IComputer createComputer(a);
}
Copy the code

Set up huawei factory, set up Xiaomi factory; Used to process corresponding products

// Huawei factory
public  class HuaWeiFactory implements TotalFactory {
    @Override
    public IPhone createPhone(a) {
        return new HuaWeiPhone();
    }
    @Override
    public IComputer createComputer(a) {
        return newHuaWeiComputer(); }}// Xiaomi factory
public  class XiaoMiFactory implements TotalFactory {
    @Override
    public IPhone createPhone(a) {
        return new XiaoMiPhone();
    }
    @Override
    public IComputer createComputer(a) {
        return newXiaoMiComputer(); }}Copy the code

Use code:

XiaoMiFactory xiaoMiFactory = new XiaoMiFactory();
IComputer computer = xiaoMiFactory.createComputer();
IPhone phone = xiaoMiFactory.createPhone();
computer.play();// Xiaomi computer
computer.study();// Xiaomi computer
computer.WatchTv();// Xiaomi computer

phone.open();// Xiaomi phone
phone.sendSMS();// Xiaomi phone
phone.wifi();// Xiaomi phone
Copy the code

Abstract Factory mode Log diagram (3.3):

\

UML class diagrams (2.3) :

Just take Huawei series as an example (too many and too messy to see more confused)

\

Advantages:

  • We only interact with the TotalFactory, you need a xiaomi phone on the new xiaomi factory, and then create the corresponding method of xiaomi phone.
  • Adhere to the open closed principle (open for extensions, closed for modifications)
  • Complies with the dependency inversion principle (interface oriented programming)

Note: I am using the Android project, have not learned Android students directly download the code, download the project you are running oh ~

The complete code

Recent articles:

Java Design Pattern Singleton (part 1)

Java Design Pattern Prototyping (PART 3)

Java Design Pattern Builder Pattern (part 4)

Java Design Pattern adapter Pattern (5)

Go to the Design Patterns/Design Principles directory page

I will update all 23 articles as soon as possible. If you want to learn design patterns, please pay attention to them.