Design Patterns : 23 Design Patterns in Java
1. The most effective idea to solve the problem.
2. is a set of repeated use, most people know, the purpose of the classification, code design experience Summary.
3. Design patterns are used for reusable code, making code easier for others to understand, and ensuring code reliability.
1. Single Case design mode :
Problem solved: Ensure that the object uniqueness of a class in memory.
For example: When multiple programs read a configuration file, it is recommended that the configuration file be encapsulated as an object. It is convenient to manipulate the data, and to ensure that multiple programs read the same profile object, it is necessary that the configuration file object is unique in memory.
The Runtime () method is designed in a single-instance design pattern.
How to ensure the uniqueness of the object?
1, do not allow other programs to create the class object.
2, create an object of this class in this class.
3, provide methods for external, let other programs get this object.
Steps:
1, because the creation of objects requires constructor initialization, as long as the constructors in this class are privatized, other programs can no longer create the class object;
2, create an object of this class in a class;
3, define a method that returns the object so that other programs can get this type of object by means of the method. (Effect: controllable)
The code reflects:
1, privatization of the constructor function;
2, create private and static objects of this class;
3, defines a public and static method that returns the object.
A Hungry man type:
Class single{
Private single () {}// privatization constructor.
private static Single S = new single (); creates a private and static object of this class.
public static single getinstance () {// defines a publicly-owned and static method that returns the object.
return s;
}
}
lazy Type: lazy loading mode.
Class single2{
Private Single2 () {}
private static Single2 s = null;
public static Single2 getinstance () {
if (s==null)
s = new Single2 ();
return s;
}
}
2. Template method design mode :
Problem solved: Some implementations are indeterminate when the internal part of the function is implemented. At this point, we can expose the uncertain parts and let the subclasses to achieve them.
Abstract class gettime{
Public final void GetTime () { //This feature can be final qualified if no replication is required
Long start = System.currenttimemillis ();
code (); ///uncertain functional parts, extracted, implemented by abstract methods
L ONG end = System.currenttimemillis ();
System.out.println ("milliseconds is:" + (End-start));
}
Public Abstract void Code (); //abstract indeterminate function, enabling sub-class replication implementation
}
Class Subdemo extends gettime{
Public Void Code () { //Sub-class replication function method
...
}
}
New Subdemo.gettime ():
Java Basics Summary 8 (design mode)