Today, we have compiled a few Java design patterns that have been learned, but also a few of the more classic common.
1 singleton mode Singelton project Development often has this demand: an object only needs to exist one (do not have new out of multiple) that is guaranteed that the class has and only one instance
There are two ways to implement a singleton pattern
(1) A Hungry man (the following is a piece of code to parse)
Class singlet{ //Construction method privatization does not allow the outside world to create private singlet () { } //static Singlet s = new singlet (); private static singlet s = new singlet (); Add private outside and cannot access (encapsulation) ///A Hungry man-type declaration give him a value to open space public static singlet GetS () { return s; }}
Class singletdemo{public static void Main (String args[]) { //singlet.s;//takes out the instance singlet S1 = Singlet.gets ();//Take out the instance
}
Parsing: The above-used a hungry man style, in order to ensure that there is only one object, then the construction method is privatized , that is, the outside world can not call to, in this class new out an object s and give him a getter method, convenient to remove this unique instance of the main class behind.
(2) Lazy-type (below a piece of code to parse)
Class singlet2{
Private Singlet () {
}
private static Singlet2 S2;
Public Static Singlet getS2 () {
if (S2 ==null) {//need to be used before creating
s2 = new Singlet2 ();
}
return s2;
}
class singletdemo{
Public static void Main (String args[]) {
Singlet2 s3 = Singlet2.gets2 ();//Take out the instance
}
}
Analysis: The lazy and a hungry man different points are,
A hungry man is an example of an instance in the establishment that gives him an accurate memory space private static singlet s = new singlet ().
Lazy type is to create an instance, give him a null, wait until you call the Getter function, then check the instance has no value, no value to create a memory space for him.
Thus, the a Hungry man style is thread-safe , the virtual machine at the beginning of the load of this part of memory space, lazy-type is thread insecure, need to add synchronization method.
Multi-use a hungry man in practical applications.
2. template mode to implement a parent class with an abstract class provides one or more common methods (subclass inheritance required) and abstract methods (requires subclass replication)
The following is a simple graphical example to parse. (uniformly print the perimeter and area of the graphic)
Abstract class tuxing{
The following two are called hook methods with the abstract method is the subclass is different, let them themselves to replicate
Abstract double Getarea ();
Abstract double getzc ();
public void print () {//Printing method is normal method, subclass inherits
System.out.println (Getarea ());
System.out.println (Getzc ());
}
}
Class juxing extends tuxing{//rectangle, inherits the graph this abstract class
private int A;
private int B;
Public juxing (int a, int b) {
THIS.A = A;
this.b = b;
}
Double Getarea () {
return a * b;
}
Double Getzc () {
return 2 * a * b;
}
}
Class Circle extends tuxing{
private int R;
Public Circle (int r) {
THIS.R = R;
}
Double Getarea () {
Return 3.14 * R * r;
}
Double Getzc () {
Return 2 * 3.14 * r;
}
}//the following main methods
public class tempdemo{
public static void Main (String args[]) {
tuxing t = new Circle (5);//Create a circle shape
T.print ();//The circumference and radius of the result output element
t = new juxing (2,3);
T.print ();
}
}
Parsing: With the general method, often need to write in a rectangular class or a circular class of printed code so that the redundancy and repetition of the code, in the form of templates, in the parent class to write the same Code method (that is, the template), this way the class must inherit, with the instance to invoke, to implement the function.
3. Simple Factory mode simply speaking, creating an instance writing the difference between a factory class screened subclass (different products in a factory)
The code analysis is as follows:
In the factory design, often need to have many of the same changes, simple Factory mode, so that will be many different in a factory class, see Code Analysis
//define a phone interface that specifies the performance protocol for the phone and a range of issues
Public interface Icellphone {
void Sendmsg ();
}
The following two classes inherit the Sendmsg method in the replication interface of a mobile interface
Class Android implements icellphone{
public void sendmsg () {
System.out.println ("Android phone send Message");
}
}
Class Iphone implements icellphone{
public void sendmsg () {
SYSTEM.OUT.PRINTLN ("Apple cell phone send message");
}
}
The following is the main class
public class Factorydemo {
Public static void Main (string[] args) {
//TODO auto-generated method stub
Icellphone p = new Android ();
p.sendmsg ()/////Android phone send SMS
/*↑ The traditional method of directly new to the phone you want
But at this point, if the need to change Android to Apple will be the above new Android () to the new IPhone (), if at this time many of the number of Android will be very troublesome */
*/* Above problems arise from the question of what cell phone to build
method: To build a "factory" to make a cell phone instead of making them see the bottom class in the main class */
p = factory.creat ("IPhone");
P.sendmsg ();//Apple Mobile Send SMS
p = factory.creat ("Android");
}
}
//The following is a mobile phone factory
class factory{
//set to static, convenient to call in parentheses to add parameters, user-friendly custom phone model
Public static Icellphone creat (String type) {
if (type.equals ("Android")) {
return new Android ();
}else if (type.equals ("IPhone")) {
return new Iphone ();
}
return null;
}
}
This is the simple factory pattern eliminates the differences between subclasses
The downside is that every time you add a new phone model, you'll want to make a judgment on the new if (Type.equals (Ooxx)) in the factory class.
The following reflection mechanism to implement a simple factory model to solve the above problems
Change the Factory mode to
public class Factory {
public static Product Getphone (String className) throws Exception, {
Return (Icellphone) Class.forName (className). newinstance ();
}
}
In the main class
p = Factory.getphone ("Package name". IPhone "); The parameter to pass in is the fully qualified name of the class
P.sendmsg ();//Apple Mobile Send SMS
p = Factory.getphone ("Package name". Android ");
4. Adapter Mode
The following is a practical example to analyze
/*
Define a window's standard
*/
Interface iwindow{
void Max ();//maximized
void min ();//Minimized
void close ();//Close
}
I made it myself. Window Mywindow, if directly inherit the interface, all the methods are to be replicated, I just want a shutdown function on it
You can consider using adapter mode at this time
form adapters,
Abstract class Windosadapter implements iwindow//uses the abstract modifier to ensure that no one else is allowed to create an adapter object
{
Allow the adapter to implement the standard and overwrite all methods, but the method body is empty
public void Max () {}
public void min () {}
public void Close () {}
}
Class Mywindow extends Windosadapter
{
Three methods should be covered
I only care about the Close method
public void Close () {
System.out.println ("Close my small Window");
}
}
Class Adapterdemo
{
public static void Main (string[] args)
{
Iwindow win = new Mywindow ();
Win.close ();
}
}
A brief analysis of several design patterns of Java programs