Depth exploration Java design patterns (e) the builder pattern depth exploration Java design patterns (b) the strategy pattern depth exploration Java design patterns (c) of the decorator pattern depth exploration Java design patterns (d) of the Flyweight

Unraveling the elaborate architecture of those things - [lesson] You Rui

Simple procedure does not require extensive design process, because they only focus on a limited solution, only a few classes. Large-scale program to focus on a wide range of design, which more than any other examples of good design properties are better utilize reusable. The idea is not only a grand provide a solution to the current problem, but was to create a design, lay the foundation for future changes. Complex program requires a lot of interaction between the thousands of lines of code and objects and users. These types of solutions typically use thousands of ATMs operated air traffic control system and the banking system found. This article is in sharp distinctions finished learning lesson JAVA architecture VIP course - after [framework] source topic of "learning the source code of good design patterns," wrote the study perception. Here, we explore the design mode called "build mode" and use Java code examples to achieve them.

Depth exploration Java design patterns (a) of singleton

Depth exploration Java design patterns (b) the strategy pattern

Depth exploration Java design patterns (c) of the decorator pattern

Depth exploration Java design patterns (d) of the Flyweight

 

Overview

Effective software design not only meet the current requirements, but also can form the basis for future change and development. Easier said than done in practice. However, the design model is undoubtedly a large extent reduce the burden on the code design. Mode is a mature framework for building flexible and maintainable software. It is set by the norms and practices standards greatly reduces the complexity of the code.

There are a number of design patterns are available, the developer can choose one optimal expression in accordance with the code stream. You do not choose not to meet the demand for products is almost impossible. In fact, the design pattern is that someone has encountered a problem and design best practices to obtain proof solution. However, they are by no means an act of God. A better idea may replace them at any time. Rebellion in a peaceful environment is suicide. While one can bail out and do their own thing, but follow a design pattern in most cases it is helpful.

 

Builder mode

Design patterns are named according to their characteristics. For example, the model builder to build lists the specifications of the class structure. Examples of particularly useful when an object oriented programming class. The idea is to construct a complex object from its representation separation. It uses the flexibility to design objects like Java. When we start coding, it is easy to feel the convenience of this design pattern.

 

Using the builder pattern

This mode is particularly useful for creating a field with many instances of the class or attribute. Evident that, in this case, the constructor is very troublesome. For example, in this class:

 1 public class Person {
 2  
 3    private final long id;
 4    private final String firstName;
 5    private final String middleName;   //optional
 6    private final String lastName;     //optional
 7    private final Date birthDate;
 8    private final String phone;
 9    private final String email;
10  
11    private final String street;       //optional
12    private final String city;         //optional
13    private final String province;
14    private final String zip;
15    // ...

 

To create an instance of this class, we can:

  • Single constructor initializes the value of a field
  • A plurality of constructors
  • After the use of non-argument constructor instantiate an object, the method using the setter

While these are valid syntax on the technology, but they are very troublesome in practice. As the number of fields, it will soon become difficult to manage and understand. Use a single constructor is a bad idea, first of all because many fields are initialized bad design with a huge parameterized constructor. Secondly, there are a number of options can be eliminated optional fields. Using multiple constructors not a good idea, because if in the future to increase the number of fields, it will soon become unmanageable.

A third approach is to not use any constructor, but delete the final qualifier from the field and use the setter method for initialization. Problem with this technique is that we can create such an invalid object using setter methods. For example, although the following is valid syntax, but it is semantically invalid class instance.

1 Person person = new Person();
2 person.setCity("Mumbai");

 

Please note that the definition of persons subject is not only valid initialization City field, and at least a non-optional fields properly initialized. This is the real problem setter method for initialization.

 

Realization builder mode

We can use the model builder to overcome all the problems discussed above. Here, through this technology, we create a companion object is called a generator. This object is used to construct supporting legitimate domain objects. This not only improves the clarity of your code, but also the structure becomes simple.

 1 public class Person {
 2    public static class Builder {
 3       private long id;
 4       private String firstName;
 5       private String middleName;     //optional
 6       private String lastName;       //optional
 7       private Date birthDate;
 8       private String phone;
 9       private String email;
10       private String street;         //optional
11       private String city;           //optional
12       private String province;
13       private String zip;
14       public Builder id(final long id) {
15          this.id = id;
16          return this;
17       }
18       public Builder firstName(final String firstName) {
19          this.firstName = firstName;
20          return this;
21       }
22       public Builder middleName(final String middleName) {
23          this.middleName = middleName;
24          return this;
25       }
26       public Builder lastName(final String lastName) {
27          this.lastName = lastName;
28          return this;
29       }
30       public Builder birthDate(final Date birthDate) {
31          this.birthDate = birthDate;
32          return this;
33       }
34       public Builder phone(final String phone) {
35          this.phone = phone;
36          return this;
37       }
38       public Builder email(final String email) {
39          this.email = email;
40          return this;
41       }
42       public Builder street(final String street) {
43          this.street = street;
44          return this;
45       }
46       public Builder city(final String city) {
47          this.city = city;
48          return this;
49       }
50       public Builder province(final String province) {
51          this.province = province;
52          return this;
53       }
54       public Builder zip(final String zip) {
55          this.zip = zip;
56          return this;
57       }
58       public Person build(){
59          if(id <= 0 || firstName.isEmpty() ||
60                birthDate == null || phone.isEmpty() ||
61                email.isEmpty() || province.isEmpty() ||
62                zip.isEmpty()){
63             throw new IllegalStateException("Cannot create
64                Person object.");
65       }
66       return new Person(id,firstName,middleName,lastName,
67          birthDate,phone,email,street,city,province,zip);
68       }
69    }
70    private final long id;
71    private final String firstName;
72    private final String middleName;     //optional
73    private final String lastName;       //optional
74    private final Date birthDate;
75    private final String phone;
76    private final String email;
77    private final String street;         //optional
78    private final String city;           //optional
79    private final String province;
80    private final String zip;
81    private Person(final long id, final String firstName,
82          final String middleName, final String lastName,
83          final Date birthDate, final String phone,
84          final String email, final String street,
85          final String city, final String province,
86          final String zip) {
87       this.id = id;
88       this.firstName = firstName;
89       this.middleName = middleName;
90       this.lastName = lastName;
91       this.birthDate = birthDate;
92       this.phone = phone;
93       this.email = email;
94       this.street = street;
95       this.city = city;
96       this.province = province;
97       this.zip = zip;
98     }
 99 }

 

Builder class is part of the class Person, Person object used to construct. For the constructor parameters ordered in a particular manner. As a result, they are passed in the same order. When using the builder pattern, order does not matter, and may be transmitted in any order value during construction. Please note that in this case, the constructor is set to private.

 1 @Test
 2 public void rightBuild() {
 3    final Person.Builder builder = new Person.Builder();
 4    final Person emp = builder
 5       .id(101)
 6       .firstName("Percy")
 7       .middleName("Bysshe")
 8       .lastName("Shelley")
 9       .birthDate(new GregorianCalendar(1792,
10          Calendar.AUGUST,4).getTime())
11       .phone("1234567890")
12       .email("[email protected]")
13       .street("123 somewhere")
14       .province("someplace")
15       .zip("10293847").build();
16 }
17 @Test(expected = IllegalStateException.class)
18 public void wrongBuild() {
19    final Person.Builder builder = new Person.Builder();
20    final Person emp = builder
21       .middleName("Bysshe")
22       .lastName("Shelley")
23       .phone("1234567890")
24       .zip("10293847").build();
25 }

 

Observed in the test method How do we create an object by calling the method call builder and a range of methods. Finally, call the build () method to end the chain and complete the creation of objects. This is what we achieve in Java code mode of ways to build.

 

in conclusion

Nature is to understand the principle behind the building mode and in their own ways. However, in all cases, the model was almost unchanged. As specified above, it must be initialized in the case where the number of fields of a class, are particularly useful builder mode. Each class is not suitable for use in this mode. As can be seen, for convenience, lines of code increases. Use it wisely cautious.

 Thanks for reading! Welcome messages. Would like to explore more in-depth study also welcome private letter to me.

Guess you like

Origin www.cnblogs.com/youruike-/p/12076008.html