The third-----of Java Advanced Design Pattern Builder mode and prototype mode

Source: Internet
Author: User
Objective

In the previous article we learned about the factory model, introducing simple factory models, factory methods, and abstract factory models. This article introduces the builder pattern and prototype pattern in the design pattern that belong to the creation pattern.

Introduction to Builders ' models

Builder mode is the creation mode. The builder mode uses multiple simple objects to construct a complex object step-by-step. This type of design pattern belongs to the Create pattern, which provides an optimal way to create an object.
The simple thing is to pull out a complex object and provide a simple call to create a different representation in the same build process. Similar to the factory model, but more focused on component assembly.

Here is an example to illustrate.
The food we eat every day has these, pancakes, bento, ramen, soya-bean milk, dairy and juice. Divided into three meals, breakfast, lunch and dinner, meals mainly include eating (commonly known as rice) and drink (soy milk, fruit juice, etc.), then we can have pancakes and soya-bean milk as breakfast, lunch box and juice as a luncheon, so we can clearly know what to eat breakfast and lunch contains what food.

First we define a food class that has two properties, food and drink.

class Meal{    private String food;    private String drinks;        public String getFood() {        return food;    }    public void setFood(String food) {        this.food = food;    }        public String getDrinks() {        return drinks;    }    public void setDrinks(String drinks) {        this.drinks = drinks;    }}

When we define food, we define a standard interface for food, and what a food contains is actually food and drink.

interface IBuilderFood{    void buildFood();    void buildDrinks();    Meal createMeal();}

The food interface defines a diet and a drinking component, and then returns the food we need through the createmeal () method.
So now we can define a breakfast and lunch.
code example:

class Breakfast implements IBuilderFood{    Meal meal;    public Breakfast(){        meal=new Meal();    }        @Override    public void buildFood() {        meal.setFood("煎饼");    }    @Override    public void buildDrinks() {        meal.setDrinks("豆浆");       }        @Override    public Meal createMeal() {        return meal;    }}class Lunch implements IBuilderFood{    Meal meal;    public Lunch(){        meal=new Meal();    }        @Override    public void buildFood() {        meal.setFood("盒饭");    }    @Override    public void buildDrinks() {        meal.setDrinks("果汁");       }        @Override    public Meal createMeal() {        return meal;    }}

After the definition is complete, the process of building breakfast and lunch is over. But this is not a builder pattern, it has a core director, which is used to create parts of complex objects, complete the creation of that part, or create it according to certain rules. So here we can create a director to create a meal. As for what meals are created, it is not necessary to know that this is a decision by the caller.

Here we can define a restaurant where you can create a meal and create a meal with a customer decision.
code example:

class FoodStore{    public Meal createBreakfast(IBuilderFood bf){        bf.buildDrinks();        bf.buildFood();        return bf.createMeal();    }}

Once we have created this director, we'll do the call test again.

code example:

public class BuilderTest {    public static void main(String[] args) {        FoodStore foodStore=new FoodStore();        Meal meal=foodStore.createBreakfast(new Breakfast());        Meal meal2=foodStore.createBreakfast(new Lunch());        System.out.println("小明早上吃的是:"+meal.getFood()+",喝的饮料是:"+meal.getDrinks());        System.out.println("小明中午吃的是:"+meal2.getFood()+",喝的饮料是:"+meal2.getDrinks());     }}

Output Result:

小明早上吃的是:煎饼,喝的饮料是:豆浆小明中午吃的是:盒饭,喝的饮料是:果汁

This article briefly introduces the operation principle of the next builder mode, which can be summarized as 4 points:

    1. Builder: Specifies an abstract interface that provides for the creation of parts required for the product, and does not involve the creation of specific object parts.

    2. ConcreteBuilder: The builder interface needs to be implemented, and different methods are created for different logic to provide an instance of the product.

    3. Director: The part used to create complex objects, complete the creation of that part, or create it according to certain rules.

    4. Product: Shows the complex object being constructed.

Usage scenarios:
It is inconvenient to apply some basic components, but the combination often changes. such as the supermarket promotional package.

Advantages:

    1. Builders are independent and easy to expand.
    2. Easy to control the risk of detail.

Disadvantages

    1. The internal structure is complex and not easy to understand.
    2. Products directly need to have common ground, the scope has control.
Prototype mode

Prototype mode (Prototype pattern) is used to create duplicate objects while guaranteeing performance. This type of design pattern belongs to the Create pattern, which provides an optimal way to create an object.

In general, we created the object directly when we created it, but the cost of creating the object was very high, and it was a bit of a bargain to create a duplicate two times, so we could use the prototype pattern.
For example, we have sent mail, in the holiday season is generally sent a blessing statement, in these blessing statements, in general, in addition to the name is not the same, most of them are the same. We can then use this pattern to create the corresponding.

Here is a simple example to illustrate.
Xiao Ming and Xiao Hong on the same day birthday, and then we need to send their mail to bless, but because of the lazy, blessing language in addition to the name is the same. At this point we can complete the blessing of the language, and then clone the blessing language, and finally according to different names to send. But here it is simple, just print it.

code example:

public class PrototypeTest {    public static void main(String[] args) {        Mail mail=new Mail();        mail.setMsg("生日快乐!");        Mail mail2=(Mail) mail.clone();        mail.setName("小明");        mail2.setName("小红");        System.out.println(mail.toString());        System.out.println(mail2.toString());    }} class Mail implements Cloneable {    private String name;    private String msg;        public String getName() {        return name;    }    public void setName(String name) {        this.name = name;    }    public String getMsg() {        return msg;    }    public void setMsg(String msg) {        this.msg = msg;    }    public Object clone() {        Object clone = null;        try {            clone = super.clone();        } catch (CloneNotSupportedException e) {            e.printStackTrace();        }        return clone;    }    @Override    public String toString() {        return name + ":" + msg ;    }    }

Output Result:

小明:生日快乐!小红:生日快乐!

After watching the prototype pattern creation, is it a feeling that cloning in Java is similar?
In fact, its core is cloning.
There are two kinds of cloning, shallow cloning and deep cloning, this article mainly introduces shallow cloning.
Shallow clone:

In a shallow clone, if the member variable of the prototype object is a value type, a copy is copied to the cloned object, and if the member variable of the prototype object is a reference type, the address of the reference object is copied to the cloned object, meaning that the member variables of the prototype object and the cloned object point to the same memory address.
In simple terms, in a shallow clone, when an object is copied, only the member variables of itself and the value types contained therein are copied, and the member objects of the reference type are not copied.
Implement the Cloneable interface and override the Clone () method in the object class;

Deep clones:

In a deep clone, regardless of whether the member variable of the prototype object is a value type or a reference type, a copy is copied to the Clone object, and a deep clone copies all the referenced objects of the prototype object to the cloned object.

In simple terms, in a deep clone, all the member variables contained in the object will be copied in addition to the object itself being copied.
Implement the Serializable interface, through the serialization and deserialization of objects to achieve cloning, you can achieve true deep cloning.

Usage scenarios:

    1. When the class initializes, it consumes a lot of resources;
    2. Getting a database connection is cumbersome;
    3. An object, when there are a lot of modifiers;

Advantages:
1. can improve performance;

Disadvantages:
1. Because the Cloneable interface must be implemented, it may be inconvenient to use.

Other music recommendations

Original is not easy, if feel good, hope to give a recommendation! Your support is my greatest motivation for writing!
Copyright notice:
Nothingness
Blog Park Source: http://www.cnblogs.com/xuwujing
csdn Source: HTTP://BLOG.CSDN.NET/QAZWSXPCM
Personal blog Source: http://www.panchengming.com
Original is not easy, please indicate the source, thank you!

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.