Design Patterns learning notes-Factory, Builder, and Prototype)

Source: Internet
Author: User


Before model learning


What is the design model: when we design the program, we gradually formed some typical problems and solutions, which is the software model; each mode describes a problem that often occurs in our program design and the solution to the problem. When we encounter the problem described by the mode, the corresponding solution can be used to solve the problem. This is the design mode.

A design pattern is an abstract thing. It is not learned but used. Maybe you don't know any pattern at all, and you don't consider any pattern, but write the best code, even from the perspective of "pattern experts", they are all the best designs and have to say "best pattern practices". This is because you have accumulated a lot of practical experience, knowing "where to write code" is a design pattern.

Some people say: "If the level is not reached, you can learn it in vain. If the level is reached, you can do it yourself ". It is true that the mode is well-developed and may still not be able to write good code, let alone design a good framework. OOP understanding and practical experience reach a certain level, and it also means to summarize a lot of good design experience, however, it may not be the case that "no teacher can do anything", or you can say that, on the basis of level and experience, it is time for the system to learn the "mode, it is helpful to learn the experts' summary and verify your own shortcomings.

This series of design patterns learning notes is actually a Learning Record for the book "Java and patterns.


Several forms of factory models
The factory mode is dedicated to instantiating a large number of classes with common interfaces. The factory model has the following forms:

(1) Simple Factory mode: Also known as Static Factory Method mode.

(2) Factory Method mode: Also known as Polymorphic Factory mode or Virtual Constructor mode. The biggest difference from the simple factory model is the polymorphism of the factory.

(3) Abstract Factory mode: Also known as Toolkit (Kit or Toolkit) mode. I personally understand it as a factory in a production factory.


Simple Factory Mode


Definition


The simple Factory mode is the class creation mode, also called the Static Factory Method mode. The simple factory mode is determined by a factory class to create a product class instance.


Structure chart




Role involved in the Mode


(1) The Creator role is the core of the simple factory model and contains the business logic closely linked to the application. The factory class creates a product object under direct calls from the client, which is often implemented by a specific Java class.

(2) Abstract Product role: the class that assumes this role is the parent class of the object created in simple factory mode or the interfaces they share. Abstract product roles can be implemented using a Java interface or Java Abstract class.

(3) The role of a specific Product: Any object created in the simple factory mode is an instance of this role. The specific Product role is implemented by a specific Java class.

Note:Abstract product roles can be omitted, factory roles and abstract product roles can be merged, and all three roles can be merged. The registered factory method can be used repeatedly for product objects (such as Singleton ). ).


Code demo

Interface Product {} class ConcreteProduct implements Product {public ConcreteProduct ();} class Creator {// static factory method public static Product factory () {return new ConcreteProduct ();}}

Advantages and disadvantages


Advantage: allows the client to be relatively independent from the product creation process, and does not need to modify the client when the system introduces a new product. That is to say, it supports the "open-close" principle to some extent.

Disadvantages: insufficient support for the "open-close" principle, because if a new product is added to the system, you need to modify the factory class, add the necessary logic to the factory class.


Application of simple factory in Java

import java.util.*;import java.text.*;class DateTest{public static void main(String[] args){Locale local = Locale.FRENCH;Date date = new Date();String now = DateFormat.getTimeInstance(DateFormat.DEFAULT,local).format(date);System.out.println(now);try{date = DateFormat.getDateInstance(DateFormat.DEFAULT,local).parse("16 nov. 01");System.out.println(date);}catch (ParseException e){System.out.println("Parsing exception:" + e);}}}

DateFormat is an abstract class. In this "simple factory mode" example, it is a combination of factory roles and abstract product roles to complete the creation of specific product roles.


Factory Method


Definition


The Factory method mode is the class creation mode, also known as the Virtual Constructor mode or the Polymorphic Factory mode.

The purpose of the factory method mode is to define a factory interface for creating product objects and postpone the actual creation to the subclass.

The factory method mode is further abstract and promoted by the simple factory mode. Due to the use of polymorphism, maintaining the advantages of a simple factory, customer service has its shortcomings, allows the system to introduce new products without modifying the specific factory role (actually adding a specific factory role ).


Structure chart


Expires + expires/MrH0 + expires/expires + CjxwPqOoMqOpvt/expires/Wwcuz6c/expires + C52LXEwt + expires/zoaM8YnI + c1_vcd4kpha + expires/ signature + signature + CjxwPqOoNKOpvt/Signature + signature/nJ + cP3tcS907/Signature + bS0vai1xMO/0ru49rbUz/Signature + signature + m/9 s/Signature/J0tSz9s/Signature + 1 xLrcz/fingerprint + 1xLj5sb6 + fingerprint + PGJyPgo8L3A + CjxoMj60 + slr0d3kv1_vadi + cjxwp1_vcd4kphbyzsbjbgfzcz0 = "brush: java; "> interface Product {} class ConcreteProduct1 implements Product {public ConcreteProduct1 () {}} class ConcreteProduct2 implements Product {public ConcreteProduct2 () {}} interface Creator {// factory method public Product factory ();} class ConcreteCreator1 implements Creator {public Product factory () {return new ConcreteProduct1 ();}} class ConcreteCreator2 implements Creator {public Product factory () {return new ConcreteProduct2 () ;}} class Client {private static Creator c1, c2; private static Product p1, p2; public static void main (String [] args) {c1 = new ConcreteCreator1 (); p1 = c1.factory (); c2 = new ConcreteCreator2 (); p2 = c2.factory ();}}

Application of factory methods in Java


Applications in the Java container class:

The Collection interface has the iterator () method and returns the Iterator interface. Each implementation class implements this iterator () method to create an Iterator-type object.

URL and URLConnection applications:

import java.net.*;import java.io.*;class URLConnectionReader{public static void main(String[] args){try{URL b = new URL("http://www.baidu.com");URLConnection c = b.openConnection();BufferedReader in = new BufferedReader(new InputStreamReader(c.getInputStream()));String s;while((s = in.readLine())!=null){System.out.println(s);}in.close();}catch (Exception e){}}}

Abstract Factory Mode


Definition

Abstract Factory mode is the most abstract and general factory mode in all forms.

Origin

The origin or earliest application of the abstract factory model is used to create windows components that belong to different operating systems.

Learn more

Abstract Factory is the factory of a factory. It can be equipped with a static method to return the instance of a specific factory (Abstract Factory type) According to parameters ).


Builder Mode


Definition

The construction mode can separate the internal representation of a product from the product generation process, so that a building process can generate product objects with different internal representations.

Structure chart


Learn more

(1) The construction mode is very similar to the abstract factory mode, both of which are used to create objects belonging to several product families at the same time.

(2) In the abstract factory model, a complete product object is returned every time a factory object is called, the client may decide to assemble these products into a bigger and more complex product, or it may not. The construction mode is different. It creates a complex product at 1.1 points, the product assembly process takes place within the builder role. In other words, the abstract factory model is in a more specific system, while the construction model is in a more macro system.


Prototype Mode


Definition

Specify the type of the object to be created by providing a prototype object, and then create more objects of the same type by copying the prototype object. this is the intention of the prototype.

Structure chart-simple original mode


Structure chart-original registration Mode


Learn more

For the prototype mode, you only need to have a deep understanding of the cloning mechanism in the Java language, deep-level cloning, and shallow-level cloning. In fact, this model is a summary of the use of clone behavior in our daily work.


Summary of the Creation Mode (Creational Pattern)


There are a total of seven creation modes, namely simple factory mode, factory method mode, abstract factory mode, construction mode, prototype mode, Singleton mode, and multi-instance mode.


This article describes five of them: simple factory, factory method, abstract factory, builder, and prototype.

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.