Java Interview 16| design pattern

Source: Internet
Author: User
Tags instance method iterable throw exception volatile log4j

1. Single Case mode:

Make sure that there is only one instance of a class, and instantiate it yourself and provide it to the entire system.

The singleton pattern has several elements:

    • Private method of construction
    • private static reference to your own instance
    • Static public method that takes its own instance as the return value

The singleton pattern is divided into two types according to the timing of the instantiated objects: one is the A Hungry man type single case, the other one is the lazy type single case. A hungry man singleton when a singleton class is loaded, it instantiates an object to its own reference, and the lazy type instantiates the object when the instance method is invoked.

A Hungry man type:

public class Singleton_simple {            private static final singleton_simple simple = new Singleton_simple ();            Private Singleton_simple () {} public            static Singleton_simple getinstance () {          return simple;      }    }

Lazy Type:

Double lock mechanism class Singleton {private volatile static Singleton singleton;public static Singleton getinstance () {if (Singleton = = NULL) {synchronized (Singleton.class) {////Because each call needs to be synchronized, it is possible to make a judgment earlier to increase efficiency, noting the use of the Singleton.class class lock if (Singleton = = NULL) {singleton = new Singleton ();}}} return singleton;}}

In order to improve efficiency. We can use double check mechanism, now look at two problems:

(1) Why double check the detection mechanism?

Since two threads can be judged by the first weight, after entering, because of the locking mechanism, there will be one thread into the synchronization block and a second judgment, while the other one is blocked at the synchronization block.

When the first thread exits the synchronization code block, the second entry, without passing a second judgment, guarantees the singleton. So you have to use a double check lock here.

In fact, there is no first judgment, we can also implement a singleton, just to consider performance problems.

(2) Why add volatile keywords to instance variables?

The Java Memory model (JMM) does not limit processor reordering, and when executing instance=new Singleton (), it is not an atomic statement, but the following three steps are actually included:

1. Allocating memory to Objects

2. Initializing the Instance Object

3. Point the reference instance to the allocated memory space

PS: Object creation can be see the "Deep Understanding Java Virtual Machine" page 44th

This three-step process does not guarantee sequential execution, and the processor will be optimized for command reordering, which is the case:

The order of execution for the optimization reflow is: 1,3,2, so that thread 1 executes to 3 o'clock, instance is not NULL, 2 is now judged Instance!=null, the instance reference is returned directly, but the instance object is not initialized yet. Thread 2 Using instance at this point may cause the program to crash.

The problem to be solved now is how to limit the processor to order optimization rearrangement.

The role of volatile:

(1) Volatile variables are not cached to register or not visible to other processors, so the most recent write value is always returned when reading a variable of type volatile.

(2) The volatile keyword can be guaranteed by providing a memory barrier to ensure that certain instruction sequence processors are not able to optimize reflow, and when the compiler generates bytecode, it inserts a memory barrier in the instruction sequence to suppress certain types of handlers from ordering.

The JVM synchronizes the actions that allocate memory space.

(1) It is possible to actually use CAS (Compare and Set) with failed retries to ensure atomicity of the update operation

(2) The memory allocation action is divided into different space according to the thread. Is that each thread pre-allocates a small chunk of memory in the Java heap,

Refer to Java Virtual Machine page 45th

In fact, there is a kind of wording, as follows:

public class Singleton {       private static class Singletonclassinstance {//private statically inner class    //may be final resolves concurrency problem, basic type declaration is available, However, when the object type, this object cannot have a state,    //If there is a state, it must be declared as final, for example, the string class is an immutable class    private static final Singleton instance = new Singleton ();   }   public static Singleton getinstance () {     return singletonclassinstance.instance;//The static inner class is called only here, and private properties make it impossible for others to use this type  }   Private Singleton () {  }}

Since Singletom does not have a static property and Singletonclassinstance is a private static inner class, it is not called by other classes, so it is not initialized in advance and implements a lazy construction instance.

Static semantics also requires that no multiple instances exist. Also, the JSL specification defines that the construction of a class must be atomic, non-concurrent, and therefore does not require the addition of synchronous blocks.  Similarly, because this construct is concurrent, getinstance () does not need to be synchronized. Virtual opportunity ensures that the <clinit> () method of a class is properly locked and synchronized in a multithreaded environment. If multiple threads initialize a class at the same time, only one thread executes the <clinit> () method of the class, and the other threads need to block the wait until the active thread executes the <clinit> () method.

The key is to know why a static inner class can guarantee a singleton: because only one thread initializes the class, static final is a constant after initialization, and of course the thread is safe.

It has important applications in practice, such as:

1. The application of single-case model in log4j. Output logs to a file must use singleton mode, otherwise overwrite the original contents of the file 2, the application in the database connection pool

 

2. Iterator mode:

Provides a way to access individual elements in a container object without exposing the object's internal details

Interface Iterable{public Iterator Iterator ();} Interface Aggregate extends Iterable{public void Add (Object obj);p ublic void Remove (object obj);p ublic Iterator Iterator ( );} Class Concreteaggregate implements Aggregate {Private list List = new ArrayList ();p ublic void Add (Object obj) {list.add (ob j);} Public Iterator Iterator () {return new concreteiterator (list);} public void Remove (Object obj) {list.remove (obj);}}

After calling the iterator () method, return a iterator iterator, implemented as follows:

Interface Iterator {public Object next ();p ublic boolean hasnext ();} Class Concreteiterator implements Iterator {Private list List = new ArrayList ();p rivate int cursor = 0;public Concreteiter Ator (List list) {this.list = list;} public Boolean Hasnext () {if (cursor = = List.size ()) {return false;} return true;} Public Object Next () {Object obj = null;if (This.hasnext ()) {obj = This.list.get (cursor++);} return obj;}}

Test it:

Aggregate AG = new Concreteaggregate (), Ag.add ("Xiaoming"), Ag.add ("Little Red"), Ag.add ("Xiao Gang"); Iterator it = Ag.iterator (); while ( It.hasnext ()) {String str = (string) it.next (); System.out.println (str);}

3. Combination design mode:

Bees are insects: inheritance implements

The bee has the act of attacking the person after moving forward: the combined implementation

Insects:

Class Insect {    private String name;    Public insect (String name) {        this.name = name;    } Public String GetName () {return name;} public void SetName (String name) {this.name = name;}}

Attack behavior:

Interface Attack {public    void Move ();    public void Attack ();} Class Attackimpl implements Attack {    private String move;    Private String attack;     Public Attack Impl (string move, String Attack) {        this.move = move;        This.attack = attack;    }    @Override public    void Move () {        System.out.println (move);    @Override public    void Attack () {        move ();        System.out.println (attack);    }}

Bees are insects that have the property of attacking people in advance:

Class Bee extends insect implements Attack {    private Attack Attack;     Public Bee (String name, Attack Attack) {        super (name);        This.attack = attack;    }     public void Move () {        attack.move ();    }     public void Attack () {        attack.attack ();    }}

Because the inheritance mechanism relies too much on the implementation details of the parent class, if the parent class changes, the subclass will follow the change, which is bad.

4. Strategy design mode:
Different Types of function Objects:interface combiner<t> {t combine (t X, t y);} public class Functional {//Calls the Combiner object on each element to combine//it with a running result, which is FINA lly returned:public static <T> T reduce (iterable<t> seq, combiner<t> combiner) {iterator<t> it = s Eq.iterator (), if (It.hasnext ()) {T result = It.next (); while (It.hasnext ()) {result = Combiner.combine (result, It.next ()) ;} return result;} If seq is the empty list:return null;  Or throw exception}//to use the above generic methods, we need to create//function objects to adapt to our particular Needs:static class Integeradder implements combiner<integer> {public integer combine (integer x, integer y) {return x + y;}} Static Class Integersubtracter implements combiner<integer> {public integer combine (integer x, integer y) {return x -Y;}} Static Class Bigintegeradder implements Combiner<biginteger> {public BigInteger combine (BigInteger x, BiGinteger y) {return x.add (y);}} public static void Main (string[] args) {//generics, VarArgs & boxing working together:list<integer> Li = Arrays . aslist (1, 2, 3, 4, 5, 6, 7); Integer result = Reduce (Li, New Integeradder ());p rint (result); 28result = Reduce (li, New Integersubtracter ());p rint (result);//Use the prime-generation facility of BIGINTEGER:LIST&L T biginteger> LBI = new arraylist<biginteger> (); BigInteger bi = biginteger.valueof (one), for (int i = 0; i < one, i++) {lbi.add (bi); bi = Bi.nextprobableprime ();} Print (LBI); BigInteger RBI = reduce (LBI, new Bigintegeradder ());p rint (RBI);}}

The example above refers to the Java programming idea for an example of a generic implementation strategy pattern.

5. Prototype design mode
Class Bottle implements Cloneable {public wine wine;public bottle (Wine wn) {this.wine = WN;} Overwrite Clone () method protected Object Clone () throws Clonenotsupportedexception {bottle Newbottle = (bottle) super.clone (); Newbottle.wine = (wine) wine.clone (); return newbottle;}} Class Wine implements cloneable {int degree; String name= "French brandy"; The string is a reference type, but when modified in a new object does not affect the original object value public int Getdegree () {return degree;} public void Setdegree (int degree) {this.degree = degree;} Overwrite Clone () method protected Object Clone () throws Clonenotsupportedexception {return Super.clone ();}}

  

Here's a summary of the specific applications of each design pattern in Java.

Structural mode

Singleton mode (single pattern)

1, log4j the log output to a file must use a singleton mode, or overwrite the original contents of the file

2. Application of database connection pool

Factory mode (Factory)

Spring Factory mode: A dependency between beans is represented by an XML file or Java annotations, and rarely is code written directly to a new class

Builder Mode (creator)

Create a container (Container) object in Struts2

Prototype mode (PROTYPE)

Cloning clone of Java ()

Structural mode

Adapter Mode (Adapter)

1. In the Java I/O class library, StringReader applies a string class to the reader interface, InputStreamReader InputStream to the reader class.

2, in the AOP in spring, because the advisor needs to be the Methodinterceptor object, each advisor in the advice should be paired with the corresponding Methodinterceptor object.

Bridging mode (bridge)

Decorative mode (Decorator)

1. Collections.synchronizedlist example is also an adorner mode

2, the application of the adorner in JUnit. Testdecorator is the decoration class for Test, and its testdecorator has some subclasses of extended functionality. such as Repeatedtest class, Testsetup class, etc.

3, under normal circumstances, need to use FileReader and StringReader, if you want to increase the cache function of the class has a lot of, then the subclass also need a lot of, so Java used the decorative mode, BufferedReader is such decorative class. In fact, all the input and output stream classes in the Java I/O library use the adorner pattern, which can be converted infinitely, and the goal is to get the stream object of the data type you want.

Pros: Dynamically extends class feature properties without the need for inheritance hierarchies, which makes it easier and more flexible to add responsibilities to classes

Combination Mode (Composite)

Appearance mode (Fa?ade)

1, in spring has provided a good package, the Org.springframework.jdbc.support package is provided under the Jdbcutils class is such a tool class

2. In hibernate configuration, there is a config class that is responsible for managing some of the information required by the runtime.

Enjoy meta mode (Flyweight)

1. Data connection pool is an important application of the meta-mode

2, in Java, the implementation of the basic type and string type to use the enjoy meta-mode

Agent mode (proxy)

1, in spring has provided a good package, the Org.springframework.jdbc.support package is provided under the Jdbcutils class is such a tool class

2. In hibernate configuration, there is a config class that is responsible for managing some of the information required by the runtime.

Behavioral patterns

Template method Mode

1. In the TestCase class in JUnit

2, in the HttpServlet of the MVC framework

3, Spring uses open processing, when using jpatemplate, only need to deal with specific SQL statements, and create a connection, close the connection and other methods do not need to write code, because do not manage what kind of persistence layer operation should be shipped, its creation and close connection are consistent, Executed in the same order, this is the application of the template method pattern

Command mode

The application of command mode in STRUTS2. Where action is the command interface in command mode, Actioninvocation is the caller of the command in command mode

Iterator mode (Iterator)

Collection, list, set, map, and so on in Java, these collections have their own iterators.

Observer mode (Oberver pattern)

Broker Mode (mediator)

Memo Mode (Memento)

Interpreter mode (interpreter)

Status mode (state)

Responsibility chain mode (Chain of Responsibility)

The responsibility chain has important application in the interceptor of STRUTS2

Policy mode (strategy)

1. The policy mode allows different algorithms to be selected during program execution. For example, when sorting, passing in different comparators (Comparator), different algorithms are used

2, Spring's resource realization thought is the typical strategy pattern application

Visitor Mode (Visitor)

1. Semantic analysis of each node of the syntax tree in Javac is implemented using the visitor pattern

  

Java Interview 16| design pattern

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.