The singleton pattern

To put it simply, there is only one instance of a class in an application, and you can’t go to new because constructors are private and usually get their instances through the getInstance() method.

The return value of getInstance() is a reference to an object, not a new instance, so don’t mistake it for multiple objects. The singleton pattern is also easy to implement, so just look at the demo

public class Singleton {



private static Singleton singleton;



private Singleton() {

}



public static Singleton getInstance() {

 if (singleton == null) {

  singleton = new Singleton();

 }

 return singleton;

}

}Copy the code

As is my custom, I’m going to comment it all out in case you don’t understand it, but this code is so simple that I didn’t comment it, so if you don’t understand a few lines of code, you can go to sleep and read my blog when you wake up and maybe you’ll understand it.

The above is the most basic method, also known as lazy writing (thread unsafe). Here are a few more singletons:


Lazy writing (thread-safe)

public class Singleton {  

   private static Singleton instance;  

   private Singleton (){}  

   public static synchronized Singleton getInstance() {  

   if (instance == null) {  

       instance = new Singleton();  

   }  

   return instance;  

   }  

}Copy the code


Hanhan style

public class Singleton {  

   private static Singleton instance = new Singleton();  

   private Singleton (){}  

   public static Singleton getInstance() {  

   return instance;  

   }  

}Copy the code




Static inner class

public class Singleton {  

   private static class SingletonHolder {  

   private static final Singleton INSTANCE = new Singleton();  

   }  

   private Singleton (){}  

   public static final Singleton getInstance() {  

   return SingletonHolder.INSTANCE;  

   }  

}Copy the code




The enumeration

public enum Singleton {  

   INSTANCE;  

   public void whateverMethod() {  

   }  

}Copy the code


This approach is advocated by Effective Java author Josh Bloch. It not only avoids multithreaded synchronization problems, but also prevents deserialization from creating new objects, which is a strong barrier, but I think it’s a bit out of touch since the enum feature was introduced in 1.5.


Double check lock

public class Singleton {  

   private volatile static Singleton singleton;  

   private Singleton (){}  

   public static Singleton getSingleton() {  

   if (singleton == null) {  

       synchronized (Singleton.class) {  

       if (singleton == null) {  

           singleton = new Singleton();  

       }  

       }  

   }  

   return singleton;  

   }  

}Copy the code

Conclusion: I personally prefer static inner class writing and hungry Chinese writing. In fact, these two methods can handle most cases. There are other ways to write it, but it depends on your business needs.


Observer model

A one-to-many dependency between objects in which all dependent objects are notified and automatically updated when an object’s state changes.

Observer pattern UML diagrams


People who can’t understand the picture come here with a small bench to give you an example: Suppose there are three people, Xiao Mei (female, 28), Lao Wang and Lao Li. Xiao Mei is very beautiful, very coquettes, Lao Wang and Lao Li are two middle-aged male diaosi, always pay attention to xiao Mei’s every move. One day, the United States said: my husband is not at home today, a person good boring ah ~ ~ ~, this sentence was heard by Lao Wang and Lao Li, the result is happy, Dally, not for a while, Lao Wang rushed to the United States small door, so entered the door …………………… . Here, Xiao Mei is the observed, Lao Wang and Lao Li are the observers, the observed sends a message, and then the observers process it accordingly, see the code:

public interface Person {

// Lao Wang and Lao Li can receive messages from xiao Hairdressing through this interface

   void getMessage(String s);

}Copy the code

This interface is equivalent to the phone numbers of Lao Wang and Lao Li. When Xiaomei sends a notice, she will call getMessage, which is the interface to call. It doesn’t matter if you don’t understand, please read down first

public class LaoWang implements Person {



Private String name = "private String name ";



   public LaoWang() {

   }



   @Override

   public void getMessage(String s) {

System.out.println(name + "+ s");

   }



}



public class LaoLi implements Person {



Private String name = "private String name ";



   public LaoLi() {

   }



   @Override

   public void getMessage(String s) {

System.out.println(name + "->" + s);

   }



}Copy the code


The code is very simple, let’s look at mei’s code:

public class XiaoMei {

   List<Person> list = new ArrayList<Person>();

    public XiaoMei(){

    }



    public void addPerson(Person person){

        list.add(person);

    }



// Go through the list and send your notification to all the people who love you

    public void notifyPerson() {

        for(Person person:list){

Person. GetMessage (" I'm the only one in the house today, so come here and whoever comes first will get me!" );

        }

    }

}Copy the code


Let’s write a test class to see if this is true

public class Test {

   public static void main(String[] args) {



       XiaoMei xiao_mei = new XiaoMei();

       LaoWang lao_wang = new LaoWang();

       LaoLi lao_li = new LaoLi();



// Lao Wang and Lao Li have registered with Xiao Mei

       xiao_mei.addPerson(lao_wang);

       xiao_mei.addPerson(lao_li);



// Xiao Mei sends a notice to Lao Wang and Lao Li

       xiao_mei.notifyPerson();

   }

}Copy the code


I took a screenshot of the results

The results

Perfect


Decorator pattern


The existing business logic is further encapsulated to add additional functions. For example, THE IO flow in Java uses decorator mode. When users use it, they can assemble it arbitrarily to achieve their desired effect. For example, I want to eat a sandwich. First, I need a big sausage. I like to eat cream. So how do we write the code? First, we need to write a Food class that all other foods inherit from. Look at the code:

public class Food {



   private String food_name;



   public Food() {

   }



   public Food(String food_name) {

       this.food_name = food_name;

   }



   public String make() {

       return food_name;

   };

}Copy the code

The code is so simple that I won’t explain it, and then we’ll write some subclasses to inherit it:

/ / bread

public class Bread extends Food {



   private Food basic_food;



   public Bread(Food basic_food) {

       this.basic_food = basic_food;

   }



   public String make() {

Return basic_food. Make ()+"+ bread ";

   }

}



/ / cream

public class Cream extends Food {



   private Food basic_food;



   public Cream(Food basic_food) {

       this.basic_food = basic_food;

   }



   public String make() {

Return basic_food. Make ()+"+ butter ";

   }

}



/ / vegetables

public class Vegetable extends Food {



   private Food basic_food;



   public Vegetable(Food basic_food) {

       this.basic_food = basic_food;

   }



   public String make() {

Return basic_food. Make ()+"+ vegetable ";

   }



}Copy the code


The constructor passes in a parameter of type Food, and then adds some logic to the make method. If you still don’t understand why this is the case, just look at my Test class

public class Test {

   public static void main(String[] args) {

Food Food = new Bread(new Vegetable(new Food(" sausage "))));

       System.out.println(food.make());

   }

}Copy the code


See no one layer encapsulation, away from you, we see: the most I new a sausage inside, outside the sausage I wrapped with a layer of cream, the cream of the outside and I add a layer of vegetables, bread, is the most I put outside is very image, ha ha ~ this design pattern is just like a real life touch, understand? So let’s look at the results

The results

One sandwich is ready


Adapter mode


Connecting two very different things together, like a transformer in real life. Suppose a mobile phone charger needs a voltage of 20V, but the normal voltage is 220V, this time need a transformer, 220V voltage into 20V voltage, so that the transformer will be 20V voltage and mobile phone.

public class Test {

   public static void main(String[] args) {

       Phone phone = new Phone();

       VoltageAdapter adapter = new VoltageAdapter();

       phone.setAdapter(adapter);

       phone.charge();

   }

}



/ / cell phone

class Phone {



public static final int V = 220; // The normal voltage is 220v, is a constant



   private VoltageAdapter adapter;



/ / charge

   public void charge() {

       adapter.changeVoltage();

   }



   public void setAdapter(VoltageAdapter adapter) {

       this.adapter = adapter;

   }

}



/ / transformer

class VoltageAdapter {

// Change the voltage function

   public void changeVoltage() {

System.out.println(" Charging...") );

Println (" original voltage: "+ Phone.V + "V");

Println (" voltage after transformer conversion :" + (phle.v-200) + "V");

   }

}Copy the code


The factory pattern

Simple Factory pattern: One abstract interface, implementation classes for multiple abstract interfaces, and one factory class for instantiating the abstract interface

// Abstract product class

abstract class Car {

   public void run();



   public void stop();

}



// Concrete implementation class

class Benz implements Car {

   public void run() {

System.out.println("Benz started... ") );

   }



   public void stop() {

System.out.println("Benz parked... ") );

   }

}



class Ford implements Car {

   public void run() {

System.out.println("Ford started... ") );

   }



   public void stop() {

System.out.println("Ford stopped... ") );

   }

}



/ / the factory class

class Factory {

   public static Car getCarInstance(String type) {

       Car c = null;

       if ("Benz".equals(type)) {

           c = new Benz();

       }

       if ("Ford".equals(type)) {

           c = new Ford();

       }

       return c;

   }

}



public class Test {



   public static void main(String[] args) {

       Car c = Factory.getCarInstance("Benz");

if (c ! = null) {

           c.run();

           c.stop();

       } else {

System.out.println(" Can't make this car..." );

       }



   }



}Copy the code

Factory method Pattern: There are four roles: Abstract Factory pattern, Concrete factory pattern, Abstract product pattern, and Concrete product pattern. Instead of instantiating a concrete product by a factory class, the product is instantiated by a subclass of the abstract factory

// Abstract product roles

public interface Moveable {

   void run();

}



// Specific product roles

public class Plane implements Moveable {

   @Override

   public void run() {

System.out.println("plane...." );

   }

}



public class Broom implements Moveable {

   @Override

   public void run() {

System.out.println("broom....." );

   }

}



// Abstract factory

public abstract class VehicleFactory {

   abstract Moveable create();

}



// Specific factory

public class PlaneFactory extends VehicleFactory {

   public Moveable create() {

       return new Plane();

   }

}



public class BroomFactory extends VehicleFactory {

   public Moveable create() {

       return new Broom();

   }

}



/ / test class

public class Test {

   public static void main(String[] args) {

       VehicleFactory factory = new BroomFactory();

       Moveable m = factory.create();

       m.run();

   }

}Copy the code


Abstract Factory pattern: Unlike the factory method pattern, where the factory produces a single product, the abstract factory pattern produces multiple products

/ Abstract factory class

public abstract class AbstractFactory {

   public abstract Vehicle createVehicle();

   public abstract Weapon createWeapon();

   public abstract Food createFood();

}

// Concrete factory class, where Food,Vehicle, Weapon are abstract classes,

public class DefaultFactory extends AbstractFactory{

   @Override

   public Food createFood() {

       return new Apple();

   }

   @Override

   public Vehicle createVehicle() {

       return new Car();

   }

   @Override

   public Weapon createWeapon() {

       return new AK47();

   }

}

/ / test class

public class Test {

   public static void main(String[] args) {

       AbstractFactory f = new DefaultFactory();

       Vehicle v = f.createVehicle();

       v.run();

       Weapon w = f.createWeapon();

       w.shoot();

       Food a = f.createFood();

       a.printName();

   }

}Copy the code

Proxy mode

There are two types, static proxy and dynamic proxy. Let’s talk about static agents. I’m not going to talk about a lot of theoretical stuff, and even if I did, you wouldn’t understand it. What real role, abstract role, proxy role, delegate role… It’s a mess. I can’t read it. When I was learning the agent mode, I went to the Internet and looked up a lot of information. When I opened the links, they were basically for you to analyze what roles there were. There were a lot of theories, which seemed very laborious. Let’s not talk about anything. Let’s talk about real life. (Note: I’m not denying theoretical knowledge here, I just think that sometimes theoretical knowledge is hard to understand, you are here to learn, not to nitpick.) After a certain age, we have to get married, and it is a very troublesome thing to get married (including those who are pushed by their parents). Rich family may look for master of ceremonies to preside over the wedding, appear lively, foreign atmosphere ~ well, now the business of wedding celebration company came, we only need to give money, wedding celebration company can help us arrange a whole set of wedding process. The process looks something like this: the family urge marriage – > the families of men and women both parties agreed to marry the day of the zodiac – > looking for a company of wedding – > at the appointed time for the wedding ceremony – > after marriage Wedding how the company intends to make the wedding program, after finished the wedding wedding company will do, we know nothing… Don’t worry, it’s not a black agent, we just give people the money, they will do the job for us. So, the wedding agency here is the proxy role, now you see what the proxy role is.

See the code implementation:

// Proxy interface

public interface ProxyInterface {

// If there are other things that need to be represented, such as eating, sleeping and going to the toilet, you can also write

void marry();

// Let others eat your own food

//void eat();

// Agent poop, own shit, let others pull it

//void shit();

}Copy the code

Civilized society, acting have a meal, acting shit of what I don’t write, have harm social decency ~ ~ ~ can understand good

Ok, let’s look at the code of the wedding company:

public class WeddingCompany implements ProxyInterface {



private ProxyInterface proxyInterface;



public WeddingCompany(ProxyInterface proxyInterface) {

 this.proxyInterface = proxyInterface;

}



@Override

public void marry() {

System.out.println(" We are from wedding company ");

System.out.println(" We are making preparations for marriage ");

System.out.println("...") );

System.out.println(" Gift purchase...") );

System.out.println("...") );

System.out.println(" I can get married ");

 proxyInterface.marry();

System.out.println(" After the marriage, we need to do follow-up processing, you can go home, the rest of our company to do ");

}



}Copy the code


See, the wedding company needs to do a lot of things, let’s look at the marriage family code:

public class NormalHome implements ProxyInterface{



@Override

public void marry() {

System.out.println(" We are married ~ ");

}



}Copy the code


This has been very obvious, the marriage family only need to get married, and the wedding company to take care of everything, before and after the things are the wedding company to do, I heard that now the wedding company is very profitable, this is the reason, the work is much, can not make money?

Let’s look at the test class code:

public class Test {

public static void main(String[] args) {

 ProxyInterface proxyInterface = new WeddingCompany(new NormalHome());

 proxyInterface.marry();

}

}Copy the code


The running results are as follows:

As we expected, the result is correct, this is static proxy, dynamic proxy I don’t want to say, related to Java reflection, there is a lot of information on the web, I will update later.

Think I write to you helpful words, click a “like” support!

I have a wechat official account, and I often share some Java technology-related dry goods. If you like my share, you can follow me by searching “Java leader” or “Javatuanzhang” on wechat.