Common design Patterns for Java------

Source: Internet
Author: User

One, single case mode

A, Singleton mode: Singleton is the simplest and most commonly used design pattern, which guarantees that a class can have only one object in memory.
Ideas:
1) If other programs are free to create the class object with new, then the number cannot be controlled. Therefore, other programs are not allowed to create objects of that class with new.
2) 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 objects.
3) This class provides the objects that are created externally (the entire system) for other programs to obtain and use.
Steps:
1) Privatize the constructors in this class.
2) Create an object of this class in this class.
3) Define a method that returns a value type that is of this class type. This method allows other programs to get to the class object.
1, a hungry man: at the beginning of the class created a new object, and the construction method is set to private, so the outside world cannot pass the way of the new object instance, only through the method of getinstance () to obtain an object instance.

Package Pattern.singleton.one;public class TestSingle {/** * @param args */public static void main (string[] args) {        Si Ngle s1=single.getinstance ();        Single s2=single.getinstance ();        System.out.println (S1==S2);}} Class Single {/** * a hungry man type *    /private static final single s=new single ();    Private single () {    } public    static getinstance () {    return s;    }}

2, lazy-type: Unlike the A Hungry man type, to call the GetInstance () method in the outside world will be a new object, which is equivalent to a delay.

public class Single2 {    /**     * Lazy-     */private static Single2 s=null;private Single2 () {}public static Single2 GetInstance () {if (s==null) {s=new Single2 ();} return s;}}

This kind of lazy style is flawed, for example, put it in a multi-threaded environment, there will be multiple threads at the same time to reach if (s==null) here to judge, then will produce a number of objects, against the singleton only to produce an object's original intention. To solve, we have to think of getinstance () in front of the synchronized mutual repulsion lock. as follows:

<pre name= "code" class= "Java" >public class Single2 {    /**     * Lazy type     */private static Single2 s=null; Private Single2 () {}public static synchronized Single2 getinstance () {//synchronized Mutex, can only be taken one by one, preventing multiple threads from getting the same instance if (s== NULL) {s=new Single2 ();} return s;}}

B, single-case Deformation---multiple examples (single buffer)
1) The use of the cache in a single case:
caching, which is used frequently in programming, has a very important role to play in enabling the program to exchange space for time, which is often designed to be a space shared by the entire application, and now requires implementing a class that stores singleton objects in a cache.
Description: The cache can hold more than one of these objects, each identified by a key value, and the key value is accessed by the same singleton object.

Import Java.util.hashmap;import Java.util.map;public class A {   private static final map<string, a> map= new Hash Map<string, a> ();   public static A getinstance (String key) {   A A = Map.get (key);   if (a==null) {   a = new A ();   Map.put (Key, a);   }   return A;   }}

2) Single-case deformation--Multiple models
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.

Import Java.util.hashmap;import Java.util.map;public class A {    //container private static final Map<integer, a> Map
   = New Hashmap<integer, a> ();p rivate static int num=1;//represents the ordinal of the object currently being used in the pool private static final int max=4;// The total number of objects that can be used in the control container is public static A getinstance () {A A = Map.get (num), if (a==null) {a = new A (); Map.put (num, a);} Num++;if (num>max) {num = 1;} return A;}}

second, the factory model

Java development is about interface-oriented programming, which requires a factory class to hide specific implementation classes

First create the interface (interface at the beginning of the design will be set, the development process is not allowed to arbitrarily change the interface):

<span style= "FONT-SIZE:14PX;" >public interface Depapi {public   String T1 (); </span><p><span style= "FONT-SIZE:14PX;" >}</span></p>
then write the implementation class:

public class DepImpl1 implements DEPAPI {@Overridepublic String t1 () {System.out.println ("Api impl1 ...."); return " 1111111 ";}}
finally create the factory class:

public class Depfactory {//factory method, naming specification: createdepapi,gedepapi,getdepinstancepublic static Depapi Getdepapi () {return new DEPIMPL1 ();}}
Test:

public class Client {public static void main (string[] args) {         Depapi API = Depfactory.getdepapi ();         System.out.println (Api.t1 ());}         }
Output Result:

Depapi impl1 ....

<span style= "FONT-SIZE:14PX;" >1111111</span>


Three, value object modein Java development, you need to swap large amounts of data back and forth, such as passing parameters to the method, and getting the return value of the method

The essence of a value object is "encapsulate data"

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

Import Java.io.serializable;public class User implements serializable{//can only write objects that support the Java.io.Serializable interface to private in the stream    String Userid;private string tel;private string address;    private int age;    Private Boolean Ismale; Public User (String userId, String tel, address of string, int age) {super (); This.userid = Userid;this.tel = tel;this.address = Address;this.age = age;} Public User () {}public String getUserId () {return userId;} public void Setuserid (String userId) {this.userid = userId;} Public String Gettel () {return Tel;} public void Settel (String tel) {This.tel = tel;} Public String getaddress () {return address;} public void setaddress (String address) {this.address = address;} public int getage () {return age;} public void Setage (int.) {this.age = age;} public Boolean Ismale () {return ismale;} public void Setmale (Boolean ismale) {This.ismale = Ismale;} @Overridepublic int hashcode () {final int prime = 31;int result = 1;result = Prime * result + (userId = = null)? 0:user 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; User other = (user) obj;if (userId = null) {if (Other.userid! = null) return false;} else if (!userid.equals (Other.userid) ) return False;return true;} @Overridepublic String toString () {return "User [userid=" + UserId + ", tel=" + Tel + ", address=" + address + ", age=" + A GE + "]";}}


Four, decorative mode

Decorating mode: The ability to dynamically extend an object without having to change the original class file and use inheritance. It is by creating a wrapper object, that is, decorating to wrap the real object.

Example: 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.

Comparison of class systems:


Import Java.io.filereader;import java.io.ioexception;import java.io.inputstreamreader;import java.io.PipedReader; Import Java.io.reader;public class Mybufferedreader extends reader{//★private Reader r;//package ★private char[] buf = new C HAR[1024];p rivate int count = 0;//records the number of characters in the current buffer private int pos = 0;//cursor, array subscript, which element of the array is currently being read public Mybufferedreader (read Er r) {//★super (); THIS.R = r;} public int Myread () throws IOException {//When the buffer is empty, use the R object into the file to read a set of data into the buffer if (count <= 0) {count = R.read (BUF); if (Count & Lt 0) {return-1;} pos = 0;} Take a character from the buffer out char ch = buf[pos];p os++;count--;return ch;} Public String Myreadline () throws IOException {StringBuilder strbuild = new StringBuilder (); int ch = 0;while ((ch = myread ())! =-1) {if (ch = = ' \ r ') {//enter continue;} if (ch = = ' \ n ') {//NewLine return strbuild.tostring ();} Strbuild.append ((char) ch);} if (Strbuild.length ()! = 0) {return strbuild.tostring ();} return null;} public void Myclose () throws IOException {R.close ();} @Overridepublic int Read (char[] cbuf, int off, int len) throws IOException {return R.read (cbuf, off, Len);} @Overridepublic void Close () throws IOException {R.close ();}}


v. DAO modeIn Java programs, it is often necessary to persist data and to obtain persisted data, but there are many problems in the process of data persistence (such as: different data sources, different storage types, different suppliers, different access modes, etc.)

DAO's Understanding:

1, DAO is actually using the combination Factory mode to solve the problem, and did not bring new functions, so learning is actually a train of thought.

2, DAO Theoretically is no layer limit.

3. In theory, there are no successive layers of DAO.


vi. application of common design patterns1. Interface-oriented programming:
1) interface-oriented programming is the first major principle.
2) in Java programming, it is very fastidious about the division of layers and the division of modules. Usually we divide the program according to three layers, respectively, the UI layer, the logical layer (named business or service), the data storage layer, they have to communicate through the interface, this layered mode in the software design with a lot of, must be paid attention to.
3) In each layer, there are many small modules, a small module external should also be a whole, then a module external should also provide interfaces, other places need to use the function of this module, should be through this interface.
2. Parameters and return values in the interface definition:1) The interface must be defined in the interface to the isolation part of the method to be exposed, for the method has parameters and the definition of the return value, in the end need to describe in the interface how to pass the parameters?
2) The Value object mode gives us a good solution. In fact, the value object has become the standard method of data exchange between different layers or different modules, which embodies the encapsulation of the data and facilitates the reuse of the object.

Common design Patterns for Java------

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.