Java and schema----creation Pattern Series Factory mode, single State mode

Source: Internet
Author: User
Tags abstract constructor final inheritance interface variables protected constructor thread
Create
Creating Patterns-----Creation pattern







The creation pattern is an abstraction of the class instantiation process.







Some systems need to dynamically determine how objects are created, what objects are created, and how they are grouped to represent objects. The creation pattern describes how these dynamic decisions are constructed and encapsulated.

Create patterns and create patterns for objects that are created and categorized.

The creation pattern of the L class: class creation mode uses inheritance relationships to defer the creation of classes to subclasses, encapsulating what specific classes the client will receive, and hiding how instances of these classes are created and put together. 、

Object creation Pattern: Object creation mode dynamically delegates the object's creation to another object, which dynamically determines which instances of specific classes the client will get, and how these instances are created and grouped together.























Factory mode







The factory pattern is responsible for instantiating a large number of classes that have a common interface. The factory model can decide which class to instantiate, without having to know in advance which class to instantiate each time.







Several forms of the factory pattern:







L Simple Factory mode. Also known as static Factory mode.







L Factory method mode. Factory method, which also antisymmetric the factory or virtual construction child mode (fictitious constructor).







L Abstract Factory mode. Abstract Factory, also known as the Toolbox (Kit or Toolkit) mode.







The step-by-step recursion of the factory pattern reflects the abstraction of the step and the resolution of the problem.







Simple Factory Factory--------















A simple factory pattern is an instance of a factory object that determines which product class to create.









General class diagram of simple factory pattern:










Factory







S-factory







+create (): c-p







P--interface

P--concrete



Create---statically

Specific Products







Abstract Products


































































The role of the Simple factory pattern design:

1. Factory Class (creator) Role: This role is the core of the factory model, and it is contained in the application of closely related business logic. The factory class creates product objects under the call of the client, and it is often implemented by a specific Java class.

2. Abstract Product Role: It provides a common interface (type) for specific products. Is the return type of the factory method.

3. Specific product (concrete product) Role: The object created by the factory method is an instance of it.









Characteristics of a simple factory pattern: Static methods return an object instance.


























Abstract Products

Specific Products






























Other class diagrams for simple factory patterns:















L This one is more extreme:! The Java class Library also has







• A large number of instances. Degenerate simple factory model.







L Second: Factory roles and abstract product merging.







































































The constructors of a single state pattern and a polymorphic schema are all private---do not provide direct instantiation of the function, they have their own static factory methods, provide their own instances.

When a single state pattern and a polymorphic pattern use a set to store objects that are created by querying the set, it becomes an application of the memo pattern.

The MVC pattern. The MVC pattern is not strictly a design pattern, but a higher level architecture pattern. The MVC pattern can be decomposed into combinations of several design patterns, including compositing patterns, policy patterns, observer patterns, and possibly decorative patterns, mediator patterns, iterative sub schemas, and factory method patterns.

The simple factory model says that objects created often belong to a product hierarchy, and that the hierarchical structure of the product makes the view in the MVC pattern, whereas the factory role itself can make the controller (Controller).


Abstractview

View

View

Controller


































































Simple Factory mode uses static factory methods, and static methods cannot be inherited by subclasses, so factory roles cannot form hierarchical structures that give inheritance. This shortcoming has been solved in the factory model.

The factory role in simple Factory mode is a key role for the system. It is the relationship between the fate of the system and the centralization of all logic. This makes the system more complex when it comes to functional expansion in the future.

The simple factory model does not support the "open and close" principle. This pattern is fully supported when the class feature of the product role expands. But when a new product role is added, the factory role has to be modified to accommodate it. It supports the principle of "opening and closing" to a limited extent.

The way the factory method returns an abstract product type is called "for abstract programming." This is the application of the principle of reliance reversal. This is done by using the superclass of the specific product class to hide its true type, the benefit of which is to provide scalability for the system. If a new specific product class is added to the system in the future, the factory class can give it to the client object for a new subclass instance without affecting the client.









































Factory method Mode







The factory method pattern is an interface that defines a factory role, deferring the creation of the century to the subclass of the factory role.

The core factory class in the factory method pattern is no longer responsible for the creation of all products, but rather the specific creation work to be done by subclasses. This core class becomes the abstract factory role. Abstract factory roles give only the interfaces that a specific factory role must implement without touching the details of which product class should be instantiated.

This further abstraction allows the factory approach model to allow the system to introduce new products without modifying the specific factory role.

Basic class diagram of factory method pattern:










Abstract Factory






Concrete Factory


P--interface

P--concrete

Create
























































The role of the factory pattern:

Abstract Factory (abstract Factory) role: This role makes the core of the factory model irrelevant to the application. Can be served by an interface or abstract class.

L Specific Factory (concrete Factory) role: The class that holds this role is the concrete class that implements the interface of the abstract factory. The specific factory role contains logic that is closely related to the application and is called by the application to create the object.

Abstract Product Role: Factory method mode says the parent type of the object being created, which is the common interface of the specific product.

• Specific product roles: This role is thought of as an interface declared by the abstract product role. Each object created by the factory method is an instance of a specific product role.

Abstract Factory pattern







Abstract Factory is the most abstract and universal form in the factory model.

The problem with the factory model is the hierarchical structure of a product, and the abstract factory needs to face the hierarchical structure of multiple products.

Class diagram of abstract factory:


Creator1















+createa:producta







+createb:productb







Creator2















+createa:producta







+createb:productb

Interface Producuta

ProducutA1







ProducutA2

Interface PRODUCUTB

ProducutB1

ProducutB2







Interface Creator















+createa:producta







+createb:productb
























































































































Abstract factories are geared toward product families in the product hierarchy:







The concrete factory Creator1 after inheriting the abstract factory creator +createa:producta +CREATEB:PRODUCTB product structure, concentrates on the product family producut*1 development.

The horizontal product family and the vertical product structure are connected by the abstract factory.















Under what circumstances the abstract factory pattern is used: [gof][Shanhong]

L A system should not rely on the details of how product instances are created, assembled, and expressed, which is critical for all forms of Factory mode.

L This system product has an excess product family, and the system consumes only one of its products. This is also the original intention of the abstract factory.

L products belonging to the same product family are used together, and this constraint must be reflected in the design of the system.

The L system provides a library of product classes, all products with the same interface, so that the client does not depend on the implementation.









Single State mode-----(Sigleton)







A single state pattern ensures that a class has only one instance of the system, and that it is instantiated and provides this instance to the entire system. This class becomes a single state class.

The main points of a single State model:







L There is only one instance of a class.







L It must create this instance on its own.







L It must provide this instance to the whole system.







L Constructor Private: not externally instantiated and not inherited.















Example of a single state mode: Resource Manager, Recycle Bin, printer resource.

Structure of a single state pattern:
































0..1

1
























































A hungry man type Single State class:







Eager singletion
-M instance:eagersingletion = new Eagersingletion ()

-eagersingletion ()///constructors are private







+getinstance (): eagersingletion//Back to this instance, static Factory method

Create








































































Code: A Hungry Man-type single State class















public class eagersingletion{

private static final eagersingletion m_instance= new Eagersingletion ();

Private Eagersingletion () {}//proprietary constructor to prevent being new

/**

* Static Factory method

*/

public static Eagersingletion getinstance () {

return m_instance;

}















}

























Lazy type of single State class:







Lazy singletion
-M Instance:lazy rsingletion = null;

-Lazysingletion ()//privatization of constructors







+getinstance (): lazysingletion//Return to this instance, static factory, thread safety

Create
















































































Code: Lazy Single-state class















public class lazysingletion{

private static final lazysingletion m_instance= null;

Private Lazysingletion () {}//proprietary constructor to prevent being new

/**

* Thread safe, static factory method, guaranteed to return a unique instance

*/

public static synchronized Eagersingletion getinstance () {

if (m_instance = null) {

M_instance = new Eagersingletion ();

}

return m_instance;

}















}









Registration type of single State class:







The register-type single State class is designed by Gof to overcome the disadvantages of not inheriting the previous two. Only its subclasses can be instantiated in a lazy way---this is immutable.























Regsingletion
-M registy:hashmap m_ registy = new HashMap ();

# regsingletion ()//constructor protection type-can be inherited by the quilt class







+getinstance (name:string): regsingletion//back to this instance

+about (): String

Create








































































































Code: Registered Single-state class/* Comment: p213 error static keyword location wrong * *















public class regsingletion{

private static HashMap m_ registy = new HashMap ();

/**

* static block, automatically loaded before class declaration

*/

static{

Regsingletion x = new Regsingletion ();

M_ Registry.put (X.getclass (). GetName (), x);

}

Protected regsingletion () {}//protected constructor, can be inherited by the quilt class!

/**

* Thread safe, static factory method, guaranteed to return a unique instance

*/

public static synchronized Regsingletion getinstance (String name) {

if (name = = null) {

Name = "Com.javaptterns.singletion.RegSingletion";

}

if (m_ registry.getname (name) = =null) {

try{

M_ Registry.put (Name,class.forname (). newinstance ());



}catch (Exception e) {









}

}

return m_instance;

}







Public String about () {









Return "Work Complete";

}

}

















Conditions for using a single state mode:







Should be used only when a system requires an instance of a given class.







Example:







Can the whole variable in the L system be placed in a single State class?







----NOT! A properly designed system should not have so-called "whole variables", which should be placed in the class corresponding to the entity they describe. If these variables are extracted and placed in an unrelated single State class, these classes will have an incorrect dependency and coupling relationship.







L The Connection object (Connection) with the database should not be designed as a single state mode. Because a database connection can have several instances.















A single state class in the Java language:







Runtime object Each Java application has a unique runtime object that enables the application to interact with the running environment. The runtime class provides a static factory method.

public static Runtime Getrntime ();

The use of runtime objects often includes executing external commands, returning existing memory, running garbage collectors, loading dynamic class libraries, and so on.

Process Pro = Runtime. Getrntime (). EXEC ("NotPad.exe");







Java.awt.Toolkit class:










Related Article

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.