Java Design Patterns (1)-------Singleton, factory, value object, decoration mode

Source: Internet
Author: User
Tags throw exception

java design mode (1)

A simple introduction to the design pattern: is a solution to the problem of an effective idea, to solve specific circumstances, recurring problems of the solution.

So why do we need to learn design patterns?

1, the design mode are some of the relatively excellent solution, many problems are typical, representative problems, learning design patterns, we do not have to solve these problems ourselves from the beginning, equivalent to the giant's shoulders, re-use these programs can, stand high see far, is to stand on the shoulders of giants to trample them down, hey.

2, the design pattern has become a common vocabulary for professionals, do not understand the unfavorable communication, can make you become very cool oh.

3, can let you design a system more professional, so that the system has a better architecture, can make you into Daniel Oh.

Several design patterns are described below:

One, a single case

If a class is required to have only one class in memory, it can be solved by a single case.

1, Ideas:

①, if other programs are free to create the class object with new, you cannot control the number. Therefore, other programs are not allowed to create objects of that class with new.
②, since no other program is new to the class object, the class will create an object within itself, or the class will never be able to create an object.
③, this class provides the objects that are created externally (the entire system) for other programs to obtain and use.

2. Steps:

①, privatize the constructors in the class.
②, create an object of this class in this class.
③, defines a method that returns a value type that is of this class type. This method allows other programs to get to the class object.

3. Code:

①, a hungry man type:

Class Single{private static final single s = new single ();p rivate A () {            }public static single getinstance () {    R Eturn s;}}
②, Lazy-type: (single example of lazy loading mode)

Class Single2 {private static Single2 s = Null;private Single2 () {            }public static Single2 getinstance () {  ///PS: If you want to If you consider thread safety, you should write this: public static synchronized Single2 getinstance () {) if (s==null) s=new Single2 (); return s;}}
4, single case deformation (multiple cases)

①, ease of use in a single case ("Singleton + cache" technology)

Requirements: The cache is used very frequently in programming, and it is very important to help the program implement space-for-time, often designed as a space shared by the entire application, and now requires implementing a class that stores singleton objects in a cache. Description: This cache can hold multiple objects of this class, each object is identified by a key value, and the key value is accessed by the same singleton object
Code:

Import Java.util.hashmap;import Java.util.map;public Class A {///define a cache (collection) to hold the data container private static Map<string,a > map = new hashmap<string,a> ();p ublic static a getinstance (String key) {A A = Map.get (key);//Determine if A exists, does not exist it is nullif (A==null) {a = new A ();//Create a new object Map.put (key, a);//Put new object into cache}return A;}}
②, single-case deformation--Multiple models ("single case + cache + Control Instance count" technology)

Requirements: The above-cached singleton is implemented as a shared space to control the number of objects for use by the entire application. The specified number of objects are maintained in the cache, and the key value of each object is specified internally by the class, and an external request is returned directly to one of the objects. Description: The equivalent of maintaining a specified number of object pools, and when the number of requests exceeds the total number of controls, the cycle begins to reuse.

Code:

Import Java.util.hashmap;import Java.util.map;public class Multiple {private static map<integer,multiple> Map = New Hashmap<integer,multiple> ();p rivate static int num=1;private static int count=3;//number of control instances: 3public static Multiple getinstance () {Multiple m = map.get (num), if (m==null) {m = new multiple (); Map.put (num, m);} num++;//if Num exceeds the number of controls, reset to 1 to recycle the objects in the cache if (Num>count) {num=1;} return m;} public static void Main (string[] args) {//test case Multiple M1 = Multiple.getinstance (); System.out.println ("M1:::" +M1); multiple m2 = multiple.getinstance (); System.out.println ("M2:::" +m2); Multiple M3 = multiple.getinstance (); System.out.println ("M3:::" +m3); Multiple M4 = Multiple.getinstance (); System.out.println ("M4:::" +M4); Multiple M5 = Multiple.getinstance (); System.out.println ("M5:::" +M5);}}

Second, the factory

1, I can be in Java program development time to pay attention to interface programming, need to hide the specific implementation of the class can be used when the design model.

2. Naming specification for factory class: ***factory; naming specification for single factory methods: GetInstance ().

3, the essence of the factory is "choose to achieve"

4, the technology boundary between the factory, the interface and the realization class: The factory is only responsible for the choice realization, realizes the class only then does the real realization, but the interface is the limit realizes what the thing and returns what thing, the tripartite division of labor is clear, accountability.

5, through the code to introduce in detail:

①, Interface API:

Interface Apipublic interface Api {public abstract String T1 ();}

②, two implementation classes IMP1 and IMP2: (all implemented interface APIs)

Class Imp1:

Implement class Implpublic Impl implements API {@Overridepublic String t1 () {return "11111111111111";//This is just a test data}}
Class IMP2:

Implement class Imp2public Impl2 implements API {@Overridepublic String t1 () {return "222222";}}
③, Factory Depfactory:

Factory Depfactory public class Depfactory {public static Api Createapi () {return new IMPL2 ();//through configuration file + class reflection, let our program depend on the string}}
④, test class (using Class):

public class Client {public static void main (string[] args) {Api obj = Depfactory.createapi ();//new Impl (); String str = OBJ.T1 (); System.out.println (str);}}

third, Value object

1, in the Java development process, the need to exchange a lot of data back and forth when you can use value Object design mode.

2, the essence of the value object is "encapsulating data"

3, the basic writing steps:

1th Step: Write a class to achieve serializable (if later data is stored in the database, then you can not serialize, save resources)
2nd step: Privatize all attributes, maintaining a default constructor method (public no parameter)
3rd Step: Provide a Get (), set () method for each property (if it is a Boolean variable, it is best to change get to IS)
4th step: Recommended overrides implement Equals (), Hashcode (), and ToString () methods

4, the Code implementation:

Import java.io.serializable;//Value Object public class Usermodel implements Serializable {//Implement serialization//privatization of all properties private String I D,name,address;private boolean man;public Usermodel (String name) {this.name = name;} Public Usermodel () {}//gives all properties a get (), set () method public String GetId () {return ID;} public void SetId (String id) {this.id = ID;} Public String GetName () {return name;} public void SetName (String name) {this.name = name;} Public String getaddress () {return address;} public void setaddress (String address) {this.address = address;} public Boolean Isman () {return mans;} public void Setman (Boolean mans) {This.man = man;} Hashcode and equals generally use only "primary key" to generate//overwrite hashcode (), Equals (), ToString () method @overridepublic int Hashcode () {final int prime = 31; int result = 1;result = Prime * result + ((id = = null)? 0:id.hashcode ()); return result;} @Overridepublic boolean equals (Object obj) {if (this = = obj) return true;if (obj = = null) return False;if (GetClass ()! = obj . GetClass ()) return false; Usermodel other = (Usermodel) obj;if (id = = NULL) {if (other.id! = null) return false;} else if (!id.equals (other.id)) return False;return true;} @Overridepublic String toString () {return "Usermodel [id=" + ID + ", name=" + name + ", address=" + address + ", man=" + ma n + "]";}}

Four, decorative mode

1, on the basis of not modifying the original object class, you need to give one or more existing class objects to provide enhanced additional functionality when you can use the decorative design mode.

2. Example:

Requirement: Write a Mybufferedreader class that enables it to enhance the functionality of character streams (such as FileReader, InputStreamReader, Pipedreader, and so on):
(1) Provide a buffered Myread () method to increase the original read () method;
(2) provides a myreadline () method that can read one line of characters at a time.
Code:

Import Java.io.filereader;import Java.io.ioexception;public class Mybufferedreader{private FileReader r;// Package (can be changed to InputStreamReader and Pipedreader, etc.) private char[] buf = new char[1024];p rivate int count=0;// Records the number of characters in the current buffer private int pos=0;//The subscript of the array element, the current read position//Constructor public Mybufferedreader (FileReader r) {THIS.R = R;} Read single character function public int myread () throws Ioexception{if (count==0) {count = R.read (buf);p os=0;} if (count==-1) {return-1;//means that the last element has been read}char ch = buf[pos];p os++;count--;return ch;} Read one line character function public String myreadline () throws Ioexception{stringbuilder sb = new StringBuilder (); int Ch=0;while ((ch=myread ())!=-1) {if (ch== ' \ R ') {continue;} if (ch== ' \ n ') {return sb.tostring ();//returns this line of String}sb.append ((char) ch) when it encounters a carriage return;} Here is the output of the string that guarantees that the last row does not have a carriage return (sb.length ()!=0)   return sb.tostring (); return null;} Throw exception function public void Close () throws Ioexception{r.close ();}}
Combine the above code with another class:

Import Java.io.bufferedreader;import Java.io.filereader;import Java.io.ioexception;public class Testmybufferedreader {    //main function public static void main (string[] args) {try {//read-only one character readtest ();//RAW Test myreadtest () ;//We write ourselves to strengthen the test//read a line readlinetest ();//RAW Test myreadlinetest ();//We write our own enhancement test} catch (IOException e) {e.printstacktrace ();}} //-------------------------------------------//
<span style= "White-space:pre" ></span>//api original method private static void Readtest () throws IOException { FileReader r = new FileReader ("A.txt"); BufferedReader br = new BufferedReader (r), int ch=0;while ((Ch=br.read ())!=-1) {System.out.print ((char) ch);} Br.close (); R.close ();}
<span style= "White-space:pre" ></span>//we wrote the enhanced version of private static void Myreadtest () throws IOException { FileReader r = new FileReader ("A.txt"); Mybufferedreader br = new Mybufferedreader (r), int ch=0;while ((Ch=br.myread ())!=-1) {System.out.print ((char) ch);} Br.close (); R.close ();} -------------------------------------------//<pre name= "code" class= "java" ><span style= "White-space: Pre "></span>//api original method
private static void Readlinetest () throws IOException {FileReader r = new FileReader ("A.txt"); BufferedReader br = new BufferedReader (r); String Line=null;while ((Line=br.readline ())!=null) {System.out.println (line);} Br.close (); R.close ();}

<span style= "White-space:pre" ></span><pre name= "code" class= "java" ><span style= "White-space: Pre "></span>//we wrote the enhanced version
private static void Myreadlinetest () throws IOException {FileReader r = new FileReader ("A.txt"); Mybufferedreader br = new Mybufferedreader (r); String Line=null;while ((Line=br.myreadline ())!=null) {System.out.println (line);} Br.close (); R.close ();}}

Copyright NOTICE: This article for Bo Master original article, without Bo Master permission not reproduced.

Java Design Patterns (1)-------Singleton, factory, value object, decoration mode

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.