Design Pattern-factory Method
The following four roles are involved in the factory method:
Abstract Factory role: any factory class that creates an object must implement this interface.
Specific factory role: this role implements the abstract factory interface and contains the application-related logic, so that the application can create the corresponding product object if it is called.
Abstract Product role: this role defines product commonalities and implements the most abstract definition of the product.
Specific product role: this role implements the interface of the abstract Product role.
Use a UML diagram to represent their relationships:
1. Abstract Factory:
package com;public interface FruitFactory { public Fruit getFruit();}
2. Abstract products:
Package com; public interface Fruit {/** get */public void get ();}
3. Specific Factory:
1. apple factory package com; public class AppleFactory implements FruitFactory {@ Override public Fruit getFruit () {// TODO Auto-generated method stub return new Apple () ;}} 2. pear factory package com; public class PearFactory implements FruitFactory {@ Override public Fruit getFruit () {// TODO Auto-generated method stub return new Pear ();}}
4. Specific Products
1. apple package com; public class Apple implements Fruit {/** Collection */public void get () {System. out. println ("Get Apple") ;}} 2. ali package com; public class Pear implements Fruit {/** Collection */public void get () {System. out. println ("Pear Collection ");}}
Test class:
Package com; public class MainClass {public static void main (String [] args) {FruitFactory fr = new AppleFactory (); // obtain the Apple instance Fruit apple = fr through AppleFactory. getFruit (); apple. get (); // get PearFacotry FruitFactory fr2 = new PearFactory (); Fruit pear = fr2.getFruit (); pear. get ();}}
Analysis: Compared with the simple factory method, the factory method follows the principle of opening and closing.
Open and closed principles: Software entities shocould be open for extension, but closed for modification.
A software entity should be open to extensions and closed to modifications.
In the previous simple factory model, to add a product type, you must modify the factory. In the factory method, if you want to add a product type (Extension) you can write a factory for the product to implement the abstract factory, then write a specific product class, and let it implement the abstract product without modifying the source code, so that the open and closed principles are followed.