To explain the builder model and prototype pattern in Java design pattern programming _java

Source: Internet
Author: User
Tags abstract generator shallow copy

Builder model
definition
Also called the generator pattern, it can abstract the construction process of complex objects (abstract categories) so that different implementations of this abstract process can construct objects of different performance (attributes).

When the algorithm for creating a complex object should be independent of the part of the object, and the construction process must allow different representations of the constructed object. We can consider using the builder model.

Realize

1. Builder specifies an abstract interface for each part of the creation of a Product object. It usually contains abstract methods for creating products and returning products, or it can be a concrete method of putting the creation process into the ConcreteBuilder class.
2. ConcreteBuilder implements the builder interface to construct and assemble the various parts of the product.
3. The Director is responsible for invoking the appropriate builders to form the product, and the Director class does not typically have a dependency relationship with the product class, and the direct interaction with the Director class is the Builder class.
4. Product represents the complex object being constructed. Concreatebuilder creates an internal representation of the product and defines its assembly process.

/** "Product" */class Pizza {private String dough = ""; 
  Private String sauce = ""; 
  
  Private String topping = ""; 
  public void Setdough (String dough) {This.dough = dough;} 
  public void setsauce (String sauce) {this.sauce = sauce;} 
 public void settopping (String topping) {this.topping = topping;} 
  
  '/** ' abstract Builder '/' abstract class PizzaBuilder {protected Pizza Pizza; 
  Public Pizza Getpizza () {return Pizza;} 
  
  public void Createnewpizzaproduct () {pizza = new pizza ();} 
  public abstract void Builddough (); 
  public abstract void Buildsauce (); 
 public abstract void buildtopping (); }/** "ConcreteBuilder" */class Hawaiianpizzabuilder extends PizzaBuilder {public void Builddough () {PIZZA.S Etdough ("Cross"); 
  public void Buildsauce () {pizza.setsauce ("mild");} 
 public void buildtopping () {pizza.settopping ("Ham+pineapple");} }/** "ConcreteBuilder" */class Spicypizzabuilder extends PIzzabuilder {public void Builddough () {pizza.setdough ("pan baked");} 
  public void Buildsauce () {pizza.setsauce (' hot ');} 
 public void buildtopping () {pizza.settopping ("Pepperoni+salami");} 
  
  "/**" Director "* *" class Waiter {private PizzaBuilder pizzabuilder; 
  public void Setpizzabuilder (PizzaBuilder pb) {pizzabuilder = PB;} 
  
  Public Pizza Getpizza () {return Pizzabuilder.getpizza ();} 
   public void Constructpizza () {pizzabuilder.createnewpizzaproduct (); 
   Pizzabuilder.builddough (); 
   Pizzabuilder.buildsauce (); 
  Pizzabuilder.buildtopping (); }/** a customer ordering a pizza. 
   * * Class Builderexample {public static void main (string[] args) {Waiter waiter = new Waiter (); 
   PizzaBuilder Hawaiian_pizzabuilder = new Hawaiianpizzabuilder (); 
  
   PizzaBuilder Spicy_pizzabuilder = new Spicypizzabuilder (); 
   Waiter.setpizzabuilder (Hawaiian_pizzabuilder); 
  
   Waiter.constructpizza (); Pizza Pizza = WaiTer.getpizza (); 

 } 
 }

The customer creates the Director object and configures it with the builder object it wants. Director obtains the customer's request to create the product, finally obtains the product.

Advantages
1. The process of constructing objects can be finely controlled to produce different product objects.
2. Easy to expand, there are new products, just add new concretebuilder can be achieved.

Related mode
The abstract factory pattern is similar to a generator because it can also create complex objects. The main difference is that the generator pattern focuses on the step-by-step construction of a complex object. The abstract factory model focuses on multiple series of product objects (simple or complex).
The generator returns the product in the final step, and for the abstract factory, the product is returned immediately.


prototype mode
definition
The prototype pattern is one of the creation patterns, characterized by a "copy" of an existing instance that returns a new instance instead of a new instance. The replicated instance is what we call "prototypes", which are customizable.
The prototype pattern is used to create complex or time-consuming instances, in which case copying an already existing instance makes the program more efficient, or creating equal values, just naming dissimilar data of the same kind.

Realize

1. Client-Creates a new object and then obtains another object via clone.
2. Prototype-Define a clone's own abstract method.
3. Concreteprototype-Implement the Clone method.

Public interface Prototype {public 
  abstract Object clone (); 
} 
 
  
 
public class Concreteprototype implements Prototype {public 
  Object clone () {return 
    super.clone (); 
  } 
} Public 
 
class Client {public 
 
  static void Main (String arg[])  
  { 
    concreteprototype obj1= new Concretepro ToType (); 
    Concreteprototype obj2 = concreteprototype) Obj1.clone (); 
  } 
 
 

Instance
1. Many of the elements in the game are duplicated, and we can replicate the same elements using the prototype pattern.
2. When making a data graph, the first time we need to save the data from the database to the object, and when we need to make other charts that have the same data, we can avoid a re-read of the database using prototype mode.

Related issues and implementation
1. If the number of prototypes that you need to create is not fixed, you can create a prototype manager that, before replicating the prototype object, will first view the client in the prototype manager
Whether there is a prototype object that satisfies the condition, and if so, use it directly, if not, clone one, a prototype pattern called the registration form.
2. There are two types of replication: deep copy and shallow copy. When shallow replication, replication objects and prototype objects share all of the internal variables of the object, and two objects have the same memory space and lifecycle. The modification of the prototype object also modifies its copy, and vice versa.

Java, as long as the implementation of the Cloneable interface can call the object class clone method to achieve shallow replication:

public class Shallowclone implements cloneable {int age; 
   
  Person of person; 
  public void Setage (int age) {this.age = age; 
  public void Setperson (String name) {person = new person (name); 
  The public Object clone () throws clonenotsupportedexception{//default Java implementation is a shallow copy return Super.clone (); 
  The public class Person {String name; 
  Public person (String name) {this.name = name; The public class Test {public static void main (string[] args) throws Clonenotsupportedexception {Shallowclon 
    E Oldshallowclone = new Shallowclone (); 
    Oldshallowclone.setage (20); 
    Oldshallowclone.setperson ("Eric"); 
     
    System.out.println ("oldname:" + OldShallowClone.person.name + "Age:" + oldshallowclone.age); 
    Shallowclone Newshallowclone = (shallowclone) oldshallowclone.clone (); 
     
    System.out.println ("newname:" + NewShallowClone.person.name + "Age:" + newshallowclone.age); 
   Oldshallowclone.age = 30; OldShallowClone.person.name = "Frank"; 
  System.out.println ("newname:" + NewShallowClone.person.name + "Age:" + newshallowclone.age); 
 } 
}

Output:

Oldname:eric age:20
newname:eric age:20
newname:frank age:20

Visible a shallow copy is a reference to an object, and when the value of the object is changed, the copied object changes, and the Java base type is the copied value.

Below we implement deep replication:

public class Deepclone {int age; 
   
  Person of person; 
  public void Setage (int age) {this.age = age; 
  public void Setperson (String name) {person = new person (name); 
    Public Deepclone (Deepclone deepclone) {this.age = Deepclone.age; 
  This.person = new Person (deepClone.person.name); Public Deepclone () {} public Object clone () throws clonenotsupportedexception{return new Deepclone (thi 
  s); } public class Test {public static void main (string[] args) throws clonenotsupportedexception {Deepclone O 
    Lddeepclone = new Deepclone (); 
    Olddeepclone.setage (20); 
    Olddeepclone.setperson ("Eric"); 
     
    System.out.println ("oldname:" + OldDeepClone.person.name + "Age:" + olddeepclone.age); 
    Deepclone Newdeepclone = (deepclone) olddeepclone.clone (); 
     
    System.out.println ("newname:" + NewDeepClone.person.name + "Age:" + newdeepclone.age); 
    Olddeepclone.age = 30; Olddeepclone.person.nAme = "Frank"; 
  System.out.println ("newname:" + NewDeepClone.person.name + "Age:" + newdeepclone.age); 
 } 
}

Output:

Oldname:eric age:20
newname:eric age:20
newname:eric age:20

In the above replication method, we recreated an object and recreated the reference to achieve a deep copy.

Advantages
1. Replication is better than new performance.
2. Simplify or hide the details of creating objects and copy them directly.

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.