Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

How to realize the factory pattern of Java design pattern

2025-02-20 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)06/01 Report--

This article introduces the relevant knowledge of "how to realize the factory pattern of Java design pattern". In the operation of actual cases, many people will encounter such a dilemma, so let the editor lead you to learn how to deal with these situations. I hope you can read it carefully and be able to achieve something!

Factory model

Objects are ubiquitous in Java applications, and they all need to be created, and if you create the new object directly, then if we want to change the object, all the new objects need to be changed. It violates the opening and closing principle in the software design principle. If we use the factory to produce objects, we only need to pay attention to the changes of the objects in the factory, so as to achieve the purpose of decoupling from the objects. the most important feature of the factory pattern is the decoupling.

Add:

Opening and closing principle: open for expansion and closed for modification. When the program needs to be extended, you can't modify the original code to achieve a hot-swappable effect. The purpose is to make the program scalable and easy to maintain and upgrade.

1. Simple factory 1.1 structure

Abstract product: defines the specification of the product and describes the main features and functions of the product.

Concrete products: implement or inherit subclasses of abstract products

Specific factory: provides a method to create a product that the caller uses to create the product.

1.2 implementation

Take ordering coffee as an example:

Coffee abstract class

Public abstract class Coffee {/ * get coffee type * @ return * / public abstract String getName (); / * * add sugar * / public void addSugar () {System.out.println ("add sugar");} / * add milk * / public void addMilk () {System.out.println ("add milk");}}

American coffee

Public class AmericanCoffee extends Coffee {@ Override public String getName () {return "American coffee";}}

Lattes

Public class LatteCoffee extends Coffee {@ Override public String getName () {return latte;}}

Coffee factory category

Public class CoffeeFactory {public Coffee createCoffee (String type) {Coffee coffee = null; if ("american" .equals (type)) {coffee = new AmericanCoffee ();} else if ("latten" .equals (type)) {coffee = new LatteCoffee ();} else {throw new RuntimeException ("no coffee of this type");} return coffee;}}

Coffee shop category

Public class CoffeeStore {public Coffee orderCoffee (String type) {CoffeeFactory factory = new CoffeeFactory (); / / call the method of producing coffee Coffee coffee = factory.createCoffee (type); coffee.addMilk (); coffee.addSugar (); return coffee;}}

Test class

Public class Test {public static void main (String [] args) {CoffeeStore coffeeStore = new CoffeeStore (); Coffee coffee = coffeeStore.orderCoffee ("latten"); System.out.println (coffee.getName ());}}

Class diagram

Coffee factories are responsible for producing coffee (specific factories), and coffee shops select coffee through coffee factories.

In fact, simple factories are often used when we actually write code. although simple factories realize the coupling between coffee shops and coffee, we can obviously see that coffee and coffee factories are coupled again. If new varieties of coffee are added in the later stage, we need to modify the code of the coffee factory, which violates the "opening and closing principle".

Note:

There is a big difference between a simple factory and not using a factory. If there are multiple coffee shops and do not use a factory, you need to modify all the coffee shops if you encounter new coffee, but you only need to modify the coffee factory to use the factory. It is similar to taking all coffee shops out of an abstract coffee shop.

1.3 advantages and disadvantages

Advantages:

Encapsulate the process of creating an object, you can obtain the object directly through parameters, separating the creation of the object from the business logic layer, so as to avoid modifying the customer code later, and it is easier to expand if you need to implement a new product to modify the factory class directly.

Disadvantages:

When adding new products, you also need to modify the code of the factory class, which violates the "opening and closing principle".

1.4 expansion

Static factory, which defines the function of creating objects in the factory class as static, so that there is no need to create the factory class, and the static method is called directly through the class name, similar to the tool class.

Public class CoffeeFactory {/ / static method public static Coffee createCoffee (String type) {Coffee coffee = null; if ("american" .equals (type)) {coffee = new AmericanCoffee ();} else if ("latten" .equals (type)) {coffee = new LatteCoffee ();} else {throw new RuntimeException ("no coffee of this type");} return coffee;} 2. Factory method

Abstract the factory, each product corresponds to a specific factory, new products only need to add the corresponding specific factory, in line with the "opening and closing principle"

2.1 structure

Abstract factory: provides an interface to create a product through which the caller accesses the factory method of the concrete factory to create the product

Concrete factory: mainly implement the abstract methods in the abstract factory and complete the creation of concrete products.

Abstract product: defines the specification of the product and describes the main features and functions of the product.

Concrete product: implement the interface defined by the abstract product, created by the concrete factory, and correspond to the concrete factory one by one

2.2 implementation

Abstract coffee and concrete coffee remain unchanged

Coffee factory (abstract factory)

Public interface CoffeeFactory {/ * create coffee * @ return * / Coffee createCoffee ();}

American Coffee Factory (specific factory)

Public class AmericanCoffeeFactory implements CoffeeFactory {/ / American coffee factory object, specializing in American coffee @ Override public Coffee createCoffee () {return new AmericanCoffee ();}}

Latte factory (specific factory)

Public class LatteCoffeeFactory implements CoffeeFactory {/ / latte factory object, specializing in producing lattes @ Override public Coffee createCoffee () {return new LatteCoffee ();}}

Coffee shop

Public class CoffeeStore {private CoffeeFactory factory; public void setFactory (CoffeeFactory factory) {this.factory = factory;} / * * order coffee * / public Coffee orderCoffee () {Coffee coffee = factory.createCoffee (); coffee.addSugar (); coffee.addMilk (); return coffee;}}

Test class

Public class Test {public static void main (String [] args) {/ / create coffee shop object CoffeeStore coffeeStore = new CoffeeStore (); / / create factory object CoffeeFactory factory = new AmericanCoffeeFactory (); coffeeStore.setFactory (factory); / / order coffee Coffee coffee = coffeeStore.orderCoffee (); System.out.println (coffee.getName ());}}

Class diagram

We only need to know the specific factory object of the coffee ordered, and the corresponding factory is called through the coffee shop, and the factory creates the coffee object to realize the process of ordering coffee.

2.3 advantages and disadvantages

Advantages:

Users only need to know the specific factory to get the products they need, and do not need to know the specific process of product creation.

When adding new products to the system, you only need to add specific product categories and corresponding specific factory classes, and there is no need to modify the original factory in accordance with the "opening and closing principle".

Disadvantages:

Each addition of a product will add a corresponding specific factory class, increasing the complexity of the system. If there are too many specific products, a large number of factory classes are not only difficult to manage, but also cause too many objects to be created in the program, seriously affecting memory performance.

3. Abstract Factory 3.1 structure

Abstract factory: provides an interface for creating products, including multiple methods for creating products, and can create multiple products of different levels.

Concrete factory: mainly to implement multiple abstract methods in the abstract factory to complete the creation of concrete products

Abstract product: defines the specification of the product, describes the main features and functions of the product, and the abstract factory pattern has multiple abstract products.

Concrete product: implement the interface defined by the abstract product, created by the concrete factory, and have a many-to-one relationship with the concrete factory.

3.2 implementation

Coffee abstract class

Public abstract class Coffee {/ * get coffee type * @ return * / public abstract String getName (); / * * add sugar * / public void addSugar () {System.out.println ("add sugar");} / * add milk * / public void addMilk () {System.out.println ("add milk");}}

American coffee

Public class AmericanCoffee extends Coffee {@ Override public String getName () {return "American coffee";}}

Lattes

Public class LatteCoffee extends Coffee {@ Override public String getName () {return latte;}}

Dessert abstract class

Public abstract class Dessert {/ / dessert abstract class public abstract void show ();}

Matcha mousse

Public class MatchaMousse extends Dessert {/ / Matcha mousse @ Override public void show () {System.out.println ("mousse");}}

Tira Misu class

Public class Tiramisu extends Dessert {/ / Tira Misu class @ Override public void show () {System.out.println ("Tira Misu");}}

Dessert factory

Public interface DessertFactory {/ * produce coffee * @ return * / Coffee createCoffee (); / * produce dessert * @ return * / Dessert createDessert ();}

American flavor dessert factory

Public class AmericanDessertFactory implements DessertFactory {/ * American dessert factory * can produce American coffee and matcha mousse * / @ Override public Coffee createCoffee () {return new AmericanCoffee ();} @ Override public Dessert createDessert () {return new MatchaMousse ();}}

Italian dessert factory

Public class ItalyDessertFactory implements DessertFactory {/ * Italian dessert factory * can produce lattes and Tira Misu * / @ Override public Coffee createCoffee () {return new LatteCoffee ();} @ Override public Dessert createDessert () {return new Tiramisu ();}}

Test class

Public class Test {public static void main (String [] args) {/ / ItalyDessertFactory factory = new ItalyDessertFactory (); AmericanDessertFactory factory = new AmericanDessertFactory (); Coffee coffee = factory.createCoffee () Dessert dessert = factory.createDessert (); System.out.println (coffee.getName ()); dessert.show ();}}

Class diagram

As can be seen from the class diagram, an abstract factory is no longer a concrete factory corresponding to a product, but a concrete factory corresponding to a product family. If you need to add a product family, you only need to add the corresponding factory class, which conforms to the "opening and closing principle".

3.3 advantages and disadvantages

Advantages:

Based on the factory method, the creation of some objects is reduced, which is suitable for application scenarios such as using only objects of the same product family at a time.

Disadvantages:

When a product needs to be added to the product family, all factories have to modify it

4. Pattern expansion

Profile + simple Factory

Decouple the factory object and the product object by means of factory mode + configuration file. Load the full class name of the configuration file in the factory class, create an object through reflection and store it in the container, if you need to get it directly from the container (Spring IOC principle)

4.1 implementation

1. Define a profile

American = com.xue.config_factory.AmericanCoffeelatten = com.xue.config_factory.LatteCoffee

two。 Improved factory class

Public class CoffeeFactory {/ * load the configuration file, get the full class name configured in the configuration file, and create an object of this class to store * / 1. Define container object to store coffee object private static HashMap map = new HashMap (); / / 2. Load configuration file static {/ / create Properties object Properties properties = new Properties (); / / call the load method in the properties object to load the configuration file InputStream is = CoffeeFactory.class.getClassLoader () .getResourceAsStream ("bean.properties"); try {properties.load (is); / / get the full class name Set keys = properties.keySet () from properties For (Object key: keys) {String className = properties.getProperty ((String) key); / / create an object by reflection Class class1 = Class.forName (className); Coffee coffee = (Coffee) class1.newInstance () / / store the name and object in the container map.put ((String) key,coffee);}} catch (Exception e) {e.printStackTrace ();}} / / get the object public static Coffee createCoffee (String name) {return map.get (name);}} by name

Static member variables are used to store the created object (the key stores the name and the value stores the corresponding object), while reading the configuration file and creating the object only need to be executed once in the static code block.

Test class

Public class Test {public static void main (String [] args) {Coffee coffee = CoffeeFactory.createCoffee ("american"); System.out.println (coffee.getName ()); System.out.println ("-"); Coffee latten = CoffeeFactory.createCoffee ("latten"); System.out.println (latten.getName ());}}

Success!

This is the end of the content of "how to implement the factory pattern of the Java design pattern". Thank you for reading. If you want to know more about the industry, you can follow the website, the editor will output more high-quality practical articles for you!

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Development

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report