Factory mode of Java Design Mode

Source: Internet
Author: User

Factory mode of Java Design Mode

Abstract: It mainly records the design patterns, static factories, simple factories, abstract factories, and BeanFactory simulation of the factory series. At the same time, they made a simple comparison of their advantages and disadvantages.

I. Introduction

What is factory? From a realistic perspective, it is the place where actual things exist, such as shipyards, paper mills, and automobile factories. Let me think about it: Oh, these lengths produce these things. Compared with our Java program, we need an Object which is usually composed of our own new Object () to generate the desired Object, but when we get the Object instance, we can only call new and use the method specified by it to produce the instance, so we want to create more things we want. what about additional operations? Answer: The Code-based factory is used to create instances instead of manual ones.

Where can I find a factory in Java code? Of course there is no real factory! The so-called factory is a way to create an instance using Java code. For example, the common Singleton mode is a static factory method, and the getInstance method is used to obtain the unique instance. this getInstance is a bit factory-like, more specifically, it is the taste of employees in the factory, because it produces instances for us.

Ii. Static factory Mode

I also know from the introduction that the singleton mode is a static factory mode. When you search for getInstance in JDK, you will find that this static factory mode is also very common in JDK. It is not necessarily a singleton. If we change the name of the class that generates the SingletonFactory, is it more appropriate? For example, how do I customize the transportation and production processes? First, we will implement a factory that produces a car and only allow this car-Car Singleton mode:

Package com. chy. dp. factory; import java. util. arrayList; import java. util. list; public class SingletonCar implements Moveable {// If only this car exists, the SingletonCar mode is private static SingletonCar; @ SuppressWarnings ("unused ") // if this List is filled, the multisample mode is private static List.
 
  
CarList = new ArrayList
  
   
(); Private SingletonCar () {} public static SingletonCar getInstance () {if (car = null) {car = new SingletonCar ();} return car ;} @ Overridepublic void run () {System. out. println ("smoke your car running... ");}}
  
 

3. Simple factory Model

1. How can we achieve custom transportation and production processes?

2. If we want to develop any transportation means, there must be polymorphism, so we need to define the abstract class factory or interface -- VehicleFactory code of a specific factory that makes transportation means:


package com.chy.dp.factory;public abstract class VehicleFactory {public abstract Moveable create();}

3. Because VehicleFactory is a transportation tool of any nature, the return of the create method cannot be a specific Transportation Tool class, but their abstract interface-Moveable code:


package com.chy.dp.factory;public interface Moveable {public void run();}

4. Since Moveable is the performance of all vehicles, all vehicles must implement this interface-Car code:


Package com. chy. dp. factory; public class Car implements Moveable {@ Overridepublic void run () {System. out. println ("smoke your car running... ");}}

5. As we mentioned above, we need a real Car and a factory dedicated to Car production to create it for us. Because we need to achieve arbitrariness, we need to produce a Car. the CarFactory of also needs to implement the VehicleFactory -- CarFactory code:


package com.chy.dp.factory;public class CarFactory extends VehicleFactory{@Overridepublic Moveable create() {return new Car();}}

6. When we have the inherent conditions above, let VehicleFactory create a simple thing for us-Client code:


package com.chy.dp.factory;public class Client {public static void main(String[] args) {VehicleFactory factory = new CarFactory();Moveable m = factory.create();m.run();}}

7. Now, the process of customized transportation and production has been achieved. For example, if we want to use an airplane in the Client, we can use VehicleFactory to create an airplane. Of course, we need to specify the aircraft style, the aircraft to be made for us, if not selected, we will provide you with a one-stop service, by default an aircraft manufacturing plant.

A) Plane:


package com.chy.dp.factory;public class Plane implements Moveable {@Overridepublic void run() {System.out.println("plan is flying...");}}

B) PlaneFactory:


package com.chy.dp.factory;public class PlaneFactory extends VehicleFactory {@Overridepublic Moveable create() {return new Plane();}}

C) Client:


package com.chy.dp.factory;public class Client {public static void main(String[] args) {//VehicleFactory factory = new CarFactory();VehicleFactory factory = new PlaneFactory();Moveable m = factory.create();m.run();}}

8. At this point, we find that we can get the desired transportation tools by making few changes to the Code, not to mention the tools, factories, and so on. This is just like you have to drive without a car. same.

Iv. Abstract Factory

1. role:

Abstract Factory controls the production of a series of products. If you want to replace a series of products, you can use abstract factories, such as many skin-changing functions and theme-changing functions. all his styles will follow theme changes, which is very similar to the role of abstract factory. The following example is used to help you understand the problem.

2. Problem Introduction

A) either only one Car or only one Plane is produced. If I want to describe how to get a Car, take AK47, and eat an apple, how can I get it? You can develop a series of products.

B) simple. Since a factory is used, let a factory create a series of products for us-DefaultFactory code:


package com.chy.dp.factory.abstractfactory;public class DefaultFactory{public Food createFood() {return new Apple();}public Vehicle createVehicle() {return new Car();}public Weapon createWeapon() {return new AK47();}}

C) an abstract class should also be used as its parent class to uniformly specify the specific production items -- Food Code: Apple code:


package com.chy.dp.factory.abstractfactory;public abstract class Food {public abstract void printName();}package com.chy.dp.factory.abstractfactory;public class Apple extends Food {public void printName() {System.out.println("apple....");}}

D) Several other JavaBean are also very similar definitions. Do not list them one by one.

E) when we want to change to another series of products, for example, to let the factory produce a set of magic brooms, magic wand, poisonous mushrooms for me, create another factory to produce another series of products-MagicFactory code:


package com.chy.dp.factory.abstractfactory;public class MagicFactory {public Food createFood() {return new MushRoom();}public Vehicle createVehicle() {return new Broom();}public Weapon createWeapon() {return new MagicStick();}}

F) when we use the second factory, we need to discard defafactory factory to create a new MagicFactory and change the following code. The key is that I don't want to change the following method. What should I do?


3. Problem Solving Process

It is very casual to abstract its parent class or interface, which is also a common interface programming.

A) abstract A factory for all our factory classes, and the production method of this factory cannot be written to death, should be implemented by sub-classes, so the return value of the method is also the abstract class or interface of the production product. -- AbstractFactory code:


Package com. chy. dp. factory. abstractfactory;/*** generate a specific product based on the specific factory * @ author Administrator **/public abstract class AbstractFactory {public abstract Vehicle createVehicle (); public abstract Weapon createWeapon (); public abstract Food createFood ();}

B) then all our factories should inherit from AbstractFactory and implement their own unique production method -- DefaultFactory code: MagicFactory code:


package com.chy.dp.factory.abstractfactory;public class DefaultFactory extends AbstractFactory{@Overridepublic Food createFood() {return new Apple();}@Overridepublic Vehicle createVehicle() {return new Car();}@Overridepublic Weapon createWeapon() {return new AK47();}}package com.chy.dp.factory.abstractfactory;public class MagicFactory extends AbstractFactory{@Overridepublic Food createFood() {return new MushRoom();}@Overridepublic Vehicle createVehicle() {return new Broom();}@Overridepublic Weapon createWeapon() {return new MagicStick();}}

C) the above factory produces things that return their common parent class types. This aims to dynamically point to the production instance, so the specific product class also needs an abstract parent class. or interface to point to the index of their specific instance. In this way, we can use their common parent class to receive messages when calling the factory. ,

D) Client:


package com.chy.dp.factory.abstractfactory;public class Client {public static void main(String[] args) {//DefaultFactory f = new DefaultFactory();AbstractFactory f = new DefaultFactory();Vehicle c = f.createVehicle();c.run();Weapon ak = f.createWeapon();ak.shoot();Food a = f.createFood();a.printName();}}


V. Comparison between simple factories and abstract factories

A simple factory can be expanded at the product latitude, that is, one or more new products can be added. However, it is very difficult to add a series of products. how many products will the factory and series have? In this way, more and more factories will emerge, and a phenomenon will emerge-factories flood!

Can an abstract factory Add a series at a time, but can it generate a new product variety? It will be very troublesome! Because you need to change the abstract factory at the top, and provide implementation for all the specific factories that have implemented it! If you have many factories, for example, there are tens of thousands! Do you dare not think about it? There is no perfect solution. On the one hand, there are more, and on the other hand, concessions must be made.

6. Simulate spring bean Factory

The simulation here is of course not all the features of BeanFacotry of spring. Instead, it only simulates one of its sub-classes: ClassPathXmlApplicationContext, which is used to parse the spring configuration file: applicationContext. some classes defined by bean labels are used in xml, and instances are created for use.

In the simulation process, another technology is used: parsing xml files. You can search for JDOM on the Internet. You can check it online and use it quickly.

1. Create a spring configuration file and place it in the com. chy. spring. factory package -- applicationContext. xml:


 
 
  
 

2. Create BeanFactory:


package com.chy.spring.factory;public interface BeanFactory {public Object getBean(String id);}

3. Create a subclass of BeanFactory -- ClassPathXmlApplicationContext:


Package com. chy. spring. factory; import java. io. inputStream; import java. util. hashMap; import java. util. list; import java. util. map; import org. jdom2.Document; import org. jdom2.Element; import org. jdom2.input. SAXBuilder; public class ClassPathXmlApplicationContext implements BeanFactory {// private Map used to store the generated bean instance
 
  
Map = new HashMap
  
   
();/*** Parse applicationContext In the constructor. xml, stored in Map * @ param fileName * @ throws Exception */public ClassPathXmlApplicationContext (String fileName) throws Exception {SAXBuilder builder = new SAXBuilder (); InputStream file = this. getClass (). getClassLoader (). getResourceAsStream (fileName); Document document = builder. build (file); // obtain the document object Element root = document. getRootElement (); // get the root node List
   
    
List = root. getChildren (); System. out. println (list. size (); for (Element e: list) {String id = e. getAttributeValue ("id"); String clazz = e. getAttributeValue ("class"); Object o = Class. forName (clazz ). newInstance (); map. put (id, o) ;}}/*** provides a method for obtaining beans. * // @ Overridepublic Object getBean (String id) {return map. get (id );}}
   
  
 

4. Copy the above Car and Moveable.

5. Configure applicationContext. xml as written in step 1.

6. Use in Client:


Package com. chy. spring. factory; import java. util. properties; public class Client {public static void main (String [] args) throws Exception {springcontextmehtodd ();} /*** simulate the spring bean factory to obtain the bean instance through the factory * @ throws Exception */private static void springcontextmehtodd () throws Exception {BeanFactory factory = new ClassPathXmlApplicationContext ("com/chy/spring/factory/applicationContext. xml "); Object o = facto Ry. getBean ("v"); Moveable m = (Moveable) o; m. run ();}/*** simulate reading the resource file to instantiate the specified bean. * @ Throws Exception */@ SuppressWarnings ("unused") private static void propertiesMethod () throws Exception {// load the resource file and obtain the value of the specified name in the resource file. Properties props = new Properties (); props. load (Client. class. getClassLoader (). getResourceAsStream ("com/chy/spring/factory/spring. properties "); String vehicleType = props. getProperty ("VehicleType"); // use Class. forName (String className) loads the class file of this class into the memory // then instantiate this class using newInstance. Object o = Class. forName (vehicleType). newInstance (); Moveable m = (Moveable) o; m. run ();}}

VII. Summary and supplement

1. Summary:


The factory is a series design model. Static factory, simple factory (or common factory), Abstract Factory. In actual design, it is not just a design pattern. There is only a more suitable design pattern and no most suitable design pattern. The two most important features of spring are IOC and AOP. From the simulation of BeanFactory, we can see that the IOC feature is to use the factory mode to help us produce beans. AOP is an application of the dynamic proxy design pattern. The last sentence does not contain any reflection framework!


2. Supplement:


The JavaBean used in the abstract factory can be built by itself, not all pasted out, and can define an abstract class (representing a type of transactions, of course you can also use interfaces) the second method pasted in the last Client simply adds that the Bean is instantiated by reading the configuration information in the resource file. This also means that in the actual project, we can dynamically specify the desired processing method through the configuration file (the Java code has been compiled into a class file) after the project has been completed.


3. structure diagram:




More: the beginning of the Java Design Pattern


Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.