[JAVA] [Gang of Four] Design pattern learning --Abstract Factory

Abstract Factory-Abstract Factory

** Table of Contents **

The basic idea of object-oriented programming is that it is better to have a low degree of coupling between objects. By using interface in java, you can make it unnecessary for the side using the concrete class to be aware of it.

interface

Screen.java


interface Screen {
    public void view();
}

** Concrete class **

TopScreen.java


public class TopScreen implements Screen {
    public void view() {
        System.out.println("the top screen");
    }
}

LoginScreen.java


public class LoginScreen implements Screen {
    public void view() {
        System.out.println("Login screen");
    }
}

** User **

Client.java


public class Client {
    public void displayTopScreen() {
        Screen top = new TopScreen()
        top.view();
    }

    public void displayLoginScreen() {
        Screen login = new LoginScreen()
        login.view();
    }
}

At first glance, there seems to be no problem, but in the parts that instantiate each class, `Screen top = new TopScreen ()` and `Screen login = new LoginScreen ()` It is absolutely necessary to be aware of the concrete class. This goes against the idea that lower coupling is better, and if you modify the constructor you are using, you will have to modify all the instantiated parts.

This is solved by creating a class that creates an instance called ``` factory class, but that factory class `` is also more flexible by separating it into an abstract class and a concrete class. This pattern is to create a new object generation factory.

Purpose

It provides an interface for creating objects that are related or dependent on each other without clarifying their concrete classes.

Component

-Define the interface that generates the AbstractFactory AbstractProduct class -Define the interface that generates the ConcreteFactory ConcreteProduct class -AbstractProduct An abstract class that extracts the common parts of the generated parts ・ ConcreteProduct Generated parts ・ Client user

Implementation

Here is the sample code. We will implement a factory that manufactures the parts necessary for the vehicle and display the vehicle to the dealer in the following flow.

The dealer requests the vehicle from the manufacturer-> The manufacturer requests the car parts from the factory-> The factory returns various parts to the manufacturer-> The manufacturer assembles the car and returns it to the dealer-> The vehicle is displayed at the dealer.

AbstractFactory Defines the interface that generates the AbstractProduct class

Car parts manufacturing plant class

CarFactory.kt


package abstractfactory

open class CarFactory {

    open fun makeEngine(displacement: Int): Engine {
        return Engine(displacement)
    }

    open fun makeTire(position: Int): Tire {
        return Tire(position)
    }

    open fun makeSteering(weight: Int): Steering {
        return Steering(weight)
    }

}

AbstractProduct An abstract class that extracts the common parts of the generated parts

Engine class

Engine.kt


package abstractfactory

open class Engine(displacement: Int) {
    open val type = "Ordinary engine"
    val displacement = displacement
}

Tire class

Tire.kt


package abstractfactory

open class Tire(position: Int) {
    open val type = "Ordinary tires"
    val position = position
}

Handle class

Steering.kt


package abstractfactory

class Steering(weight: Int) {
    val type = "Ordinary handle"
    val weight = weight
}

Car class

Car.kt


package abstractfactory

open class Car(type: String, engine: Engine, tire: Tire, steering: Steering) {
    val type = type
    val engine = engine
    val tire = tire
    val steering = steering

    fun getConstitution(): String {
        return  "[Vehicle type]:" + type + "," +
                "【engine】:" + engine.type + "," +
                "【tire】:" + tire.type + "," +
                "【handle】:" + steering.type
    }
}

Client user

Automaker class

Maker.kt


package abstractfactory

class Maker {

    /**
     *Ordinary car manufacturing
     */
    fun getCar(): Car {
        return make("Family car", CarFactory())
    }

    /**
     *Manufacturing
     */
    private fun make(type: String, factory: CarFactory): Car {
        val engine = factory.makeEngine(1000)
        val tire = factory.makeTire(1)
        val steering = factory.makeSteering(100)

        return Car(type, engine, tire, steering)
    }

}

Car dealer class

AutomobileDealer.kt


package abstractfactory

class AutomobileDealer {

    val cars = mutableListOf<Car>()

    init {
        openingUp()
    }

    /**
     *List of cars at dealers
     */
    fun showCars() {
        cars.forEach {
            println(it.getConstitution())
        }
    }

    /**
     *Store opening
     */
    private fun openingUp() {
        val maker = Maker()
        cars.add(maker.getCar())
    }
}

Output result

If you call AutomobileDealer # showCars (), the displayed vehicle (spec) will be output.

[output]
[Vehicle type]: Family car,[Engine]: Ordinary engine,[Tire]: Ordinary tire,[Handle]: Ordinary handle

It was completed with the above, but suddenly the president said that he should build a factory that can also manufacture parts for supercars on the same line while keeping the existing production line.

ConcreteFactory Defines the interface that generates the ConcreteProduct class

Super car parts manufacturing factory class

SuperCarFactory.kt


package abstractfactory

class SuperCarFactory: CarFactory() {

    override fun makeEngine(displacement: Int): Engine {
        return HiPerformanceEngine(displacement)
    }

    override fun makeTire(position: Int): Tire {
        return HiGripTire(position)
    }
}

ConcreteProduct Generated parts

High power engine class

HiPerformanceEngine.kt


package abstractfactory

class HiPerformanceEngine(displacement: Int): Engine(displacement) {
    override val type = "High power engine"
}

High grip tire class

HiGripTire.kt


package abstractfactory

class HiGripTire(position: Int): Tire(position) {
    override val type = "High grip tire"
}

Add a supercar manufacturing method to the manufacturer.

Client user

Manufacturer class

Maker.kt


package abstractfactory

class Maker {

    /**
     *Car manufacturing
     */
    fun getCar(): Car {
        return make(CarFactory())
    }

    /**
     *Supercar manufacturing
     */
    fun getSuperCar(): Car {
        return make("Super car", SuperCarFactory())
    }

    /**
     *Manufacturing
     */
    private fun make(type: String, factory: CarFactory): Car {
        val engine = factory.makeEngine(1000)
        val tire = factory.makeTire(1)
        val steering = factory.makeSteering(100)

        return Car(type, engine, tire, steering)
    }

}

The dealer demands a new vehicle (supercar) from the manufacturer.

AutomobileDealer.kt


package abstractfactory

class AutomobileDealer {

    val cars = mutableListOf<Car>()

    init {
        openingUp()
    }

    /**
     *List of cars at dealers
     */
    fun showCars() {
        cars.forEach {
            println(it.getConstitution())
        }
    }

    /**
     *Store opening
     */
    private fun openingUp() {
        val maker = Maker()
        cars.add(maker.getCar())
        cars.add(maker.getSuperCar())
        cars.add(maker.getSuperCar())
    }
}

If you call AutomobileDealer # showCars (), you can see that the supercar is newly displayed.

Output result

[output]
[Vehicle type]: Family car,[Engine]: Ordinary engine,[Tire]: Ordinary tire,[Handle]: Ordinary handle
[Vehicle type]: Supercar,[Engine]: High-power engine,[Tire]: High grip tire,[Handle]: Ordinary handle
[Vehicle type]: Supercar,[Engine]: High-power engine,[Tire]: High grip tire,[Handle]: Ordinary handle

With the above, we were able to meet the president's request.

Recommended Posts

[Gang of Four] Design pattern learning --Abstract Factory
[Gang of Four] Design pattern learning --Factory Method
[Gang of Four] Design pattern learning
[Gang of Four] Design pattern learning --Singleton
[Gang of Four] Design Pattern Learning --Decorator
[Gang of Four] Design pattern learning --Visitor
[Gang of Four] Design pattern learning --Mediator
[Gang of Four] Design pattern learning --Iterator
[Gang of Four] Design pattern learning --Facade
[Gang of Four] Design pattern learning --Composite
[Gang of Four] Design pattern learning --Prototype
[Gang of Four] Design pattern learning --Memento
[Gang of Four] Design pattern learning --State
[Gang of Four] Design pattern learning --Interpreter
[Gang of Four] Design pattern learning --Builder
[Gang of Four] Design pattern learning --Bridge
[Gang of Four] Design pattern learning --Proxy
[Gang of Four] Design pattern learning --Strategy
[Gang of Four] Design pattern learning --Adapter
[Gang of Four] Design pattern learning --Observer
[Gang of Four] Design pattern learning --Command
[Gang of Four] Design pattern learning --Fly Weight
[Gang of Four] Design pattern learning --Chain of Responsibility
[Gang of Four] Design pattern learning --Template Method
Design Pattern #Factory Method
Learn the design pattern "Abstract Factory" in Python
Design patterns to enjoy with frequently used Java libraries --Abstract Factory pattern
Gang of Four (GoF) Patterns in Python
Pattern recognition learning in video Part 1 Field of Pattern Recognition
Learn the design pattern "Factory Method" in Python
Design Pattern #Builder
Design Pattern #Adapter
Design Pattern #Decorator
Design Pattern #Observer
Design Pattern #Facade
Design Pattern #Strategy
Design Pattern #Singleton
Design Pattern #Proxy
I wrote a design pattern in kotlin Factory edition
Learn the design pattern "Chain of Responsibility" in Python