Java - Factory Design Patterns

Posted by 758 on Fri, 02 Aug 2019 05:12:56 +0200

Polymorphism:

Method Polymorphism

Method overloading

2. Method overwriting

Object polymorphism

3. Inheritance of abstract classes

4. Implementation of Interface

Coupling: When the code changes, the client needs to adjust accordingly.

Factory design pattern:

1. Simple Factory Mode (Defining a Static Method): Creating a New Class of the Department and Decoupling the Client

Simple factory pattern: Specially define a class to create instances of other classes, which usually have a common parent class. Here we are equivalent to creating a computer factory, customers need to buy what kind of computer, as long as the input type number can get the computer. It is easy to decouple the instantiation of a class to the factory.

The instantiated object of a class is handed over to the factory, and the instances created usually have a common parent class (inheriting Abstract classes/implementation interfaces).

Summary: 1. An abstract product class 2. Specific product classes (multiple) 3. A factory (used to create different specific classes)

Advantages: Simple and easy to implement, instantiating classes to factories, easy to decouple

Disadvantage: Adding specific products requires modifying factories in violation of OCP Open Closure Principle

2. Factory Method Patterns (Defining Method in Factory): Factory Method Patterns provide a factory class for each product and determine which factory class to use to create objects in the client.

Factory Method Patterns: Define an interface for creating objects, let subclasses decide which class to instantiate, and let subclasses decide which class to delay instantiation to subclasses.

The factory method pattern provides a factory class for each product and determines which factory class to use to create objects on the client side.

We abstract the previous CompputerFactory into an interface, and then create specific factory classes to implement the interface.

Summary 1. An abstract product class 2. More than one specific product class 3. An abstract factory 4. More than one specific factory - each specific product corresponds to a specific factory.

Advantages: Reducing code coupling, object generation to subclasses to complete; Implementing the principle of open and closed - each time adding subproducts do not need to modify the original code

Disadvantage: Increased code volume, each specific product requires a specific factory; when adding Abstract products, that is, adding another product family, it needs to modify the factory against OCP.

3. Abstract Factory Model

At this time, the product manager in charge of the plant said that he would produce a new class of product operating systems, Mac Os and Windows 8. At this time, the abstract factory model was extended.

Abstract factory pattern: provides an interface for creating a series of related or interdependent objects without specifying their specific classes.

The factory method pattern is basically similar to the abstract factory pattern. It can be understood that when a factory produces only one product, it is the factory method pattern, and if a factory produces two or more goods, it becomes the abstract factory pattern.

We add the method of creating system in abstract factory interface and implement it by instance factory class.

Summary 1. Multiple abstract product classes 2. Specific product classes 3. Method of returning Abstract products by abstract factory class-declaration (group). 4. Specific factory class-generation (group) of specific products

Advantage:

Code decoupling

Achieving multiple product families (family of related products), while a single product of the factory method pattern can meet more production needs.

Satisfies OCP's Open and Closed Principle very well

In the abstract factory pattern, we can define and implement more than one interface. A factory can also generate more than one product class for the production of complex objects.

Quite flexible and scalable

Disadvantages:

Extending the product family is cumbersome and violates OCP because all factories have to be modified.

Since the abstract factory pattern is an extension of the factory method pattern, it is generally cumbersome.

summary

The greatest advantage of the simple factory model is that the factory has specific logic to determine what products are generated, and the instantiation of classes is handed over to the factory.

What products we need only need to modify the factory calls without modifying the client, which reduces the dependence on specific products for the client.

The factory method pattern is an extension of the simple factory. The factory method pattern gives the client the logical judgment to realize that class in the original simple factory.

If you just need to modify customers and add specific functions like adding functions, you don't need to modify the previous classes.

The abstract factory pattern further extends the factory method pattern, by which only one abstract product can be added to the original factory method pattern and no product family can be added.

The drawbacks are overcome. The abstract factory model not only follows the OCP principle, but also can add more products (abstract products), and the concrete factory is not only the OCP principle.

A single product can be generated, but a set of products can be generated. An abstract factory also declares a set of products, which is more flexible for extension, but if it is an extension family.

Department will be very heavy.

Typical operations using factory mode in JDK:

1. iterator method in Collection (iterator in collection class)

2. sql-related operations in java.util packages

Simple factory mode VS factory method mode:

For the simple factory model, the logical judgment of creating objects is placed in the factory class, the customer does not perceive the specific class, but it violates the open-close principle. If we want to add new specific classes, we must modify the factory class. For the factory method mode, it adds specific classes through expansion, which conforms to the open-close principle. But in the client side, it must be aware of the specific factory class, that is, to move the judgment logic from the factory class of a simple factory to the client side. It is very convenient to expand the factory method horizontally. If the factory has a new product Macbook Air to produce, it only needs to create the corresponding factory class and product class to implement the abstract factory interface and abstract product interface, instead of modifying the existing code.

	public class Factory{
		public static void main(String[] args){
			Client client = new Client();
			client.buy(new Mac());
			client.buy(new Dell());
		}
	}
	
	class Client{
		public void buy(Computer computer){
			computer.printComputer();
		}
	}
	
	interface Computer{
		void printComputer();
	}
	
	class Mac implements Computer{
		public void printComputer(){
			System.out.println("This is one. Mac"); }
	
	class Dell implements Computer{
		public void printComputer(){
			System.out.println("This is one. Dell");
		}
	}

 

This code is highly coupled. When adding new computer types, the client will also change - ----> Simple Factory Mode

I. Simple Factory Model

	public class Factory{
		public void buy(Computer computer){
			if(computer==null){
				return;
			}
			computer.printComputer();
		}
		public static void main(String[] args){
			Factory  client = new Factory();
			client.buy(SimpleComputerFacyory.getInstance("mac"));
			client.buy(SimpleComputerFacyory.getInstance("dell"));
			client.buy(SimpleComputerFacyory.getInstance(""));
		}
	}
	
	class SimpleComputerFacyory{
		public static Computer getInstance(String type){
			switch(type){
				case "mac":
					return new Mac();
				case "dell":
					return new Dell();
				default:
					System.out.println("meiyouzhegeleixing ");
					return null;
			}
		}
	}
	
	interface Computer{
		void printComputer();
	}
	
	class Mac implements Computer{
		public void printComputer(){
			System.out.println("This is one. Mac");
		}
	}
	
	class Dell implements Computer{
		public void printComputer(){
			System.out.println("This is one. Dell");
		}
	}

 

II. Factory Method Model

	public class Factory{
		public static void main(String[] args){
			Client client = new Client();
			MacFactory macFactory = new MacFactory();
			Computer computer = macFactory.createComputer();
			client.buy(computer);
		}
	}
	class Client{
		public void buy(Computer computer){
			if(computer==null){
				return;
			}
			computer.printComputer();
		}
	}
	
	interface Computer{
		void printComputer();
	}
	interface MethodComputerFactory{
		Computer createComputer();
	}
	
	class Mac implements Computer{
		public void printComputer(){
			System.out.println("This is one. Mac");
		}
	}
	class MacFactory implements MethodComputerFactory{
		public Computer createComputer(){
			return new Mac();
		}
	}
	
	class Dell implements Computer{
		public void printComputer(){
			System.out.println("This is one. Dell");
		}
	}
	class DellFactory implements MethodComputerFactory{
		public Computer createComputer(){
			return new Dell();
		}
	}

 

3. Abstract Factory Model

interface ISubject { 
    public void buyComputer() ; // The core function is to buy a computer. 
}
class RealSubject implements ISubject { 
    public void buyComputer() { 
        System.out.println("Buy an alien computer") ; 
    } 
}
class ProxySubject implements ISubject { 
    private ISubject subject ; // Real Operating Business 
    public ProxySubject(ISubject subject) { 
        this.subject = subject ; 
    }
    public void produceComputer() { 
        System.out.println("1.Production of Alien Computers") ; 
    }
    public void afterSale() { 
        System.out.println("3.Alien Computer Aftersales Team") ; 
    }
    public void buyComputer() { 
        this.produceComputer() ; // Prepare for real operation 
        this.subject.buyComputer() ; // Calling Real Business 
        this.afterSale() ; // End of operation 
    } 
}
class Factory { 
    public static ISubject getInstance(){ 
        return new ProxySubject(new RealSubject()) ; 
    } 
}
public class Test{ 
    public static void main(String[] args) { 
        ISubject subject = Factory.getInstance() ; 
        subject.buyComputer() ; 
    } 
}

Reflective factory mode: add new subclasses without changing code. (Simple factory): When adding a new subclass, the open-close principle is realized by modifying the factory code.

public class FactoryAndReflect {
    public static void main(String[] args) {
        Factory.getInstance("reflect.WaterMelon").eat();
    }
}

class Factory{
    public static IFruit getInstance(String fruitName) {
        IFruit fruit = null;
        Class<?> cla = null;
        try {
            cla = Class.forName(fruitName);
            try {
                fruit = (IFruit) cla.newInstance();
            } catch (InstantiationException e) {
                e.printStackTrace();
            } catch (IllegalAccessException e) {
                e.printStackTrace();
            }
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        }

        return fruit;
    }
}

interface IFruit{
    void eat();
}

class Apple implements IFruit {

    @Override
    public void eat() {
        System.out.println("eat an apple");
    }
}

class Orange implements IFruit {

    @Override
    public void eat() {
        System.out.println("eat an Orange");
    }
}

class WaterMelon implements IFruit {

    @Override
    public void eat() {
        System.out.println("eat a WaterMelon");
    }
}

 

Topics: Mac Windows JDK SQL