In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-03-30 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Internet Technology >
Share
Shulou(Shulou.com)06/01 Report--
This article mainly introduces "what are the commonly used web design patterns". In the daily operation, I believe that many people have doubts about the commonly used web design patterns. The editor consulted all kinds of materials and sorted out simple and easy-to-use operation methods. I hope it will be helpful to answer the questions of "what are the commonly used web design patterns?" Next, please follow the editor to study!
Singleton mode
To put it simply, in an application, there is only one instance object of a class, and you have no way to new, because the constructor is modified by private, usually through the getInstance () method to get their instances. The return value of getInstance () is a reference to an object, not a new instance, so don't misinterpret it as multiple objects. The singleton pattern is also easy to implement. Just look at demo.
Public class Singleton {private static Singleton singleton; private Singleton () {} public static Singleton getInstance () {if (singleton = = null) {singleton = new Singleton ();} return singleton;}}
According to my habit, I want to be full of comments, in case you don't understand, but this code is so simple that I didn't write any comments. If you can't understand these lines of code, you can wash up and sleep. Maybe you can read my blog when you wake up.
The above is the most basic way of writing, also known as lazy writing (thread unsafe). Next, I'll publish a few more singleton patterns:
Public class Singleton {private static Singleton instance; private Singleton () {} public static synchronized Singleton getInstance () {if (instance = = null) {instance = new Singleton ();} return instance }} public class Singleton {private static Singleton instance = new Singleton (); private Singleton () {} public static Singleton getInstance () {return instance;}} 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;}} enumerate public enum Singleton {INSTANCE; public void whateverMethod () {}}
This approach is advocated by Josh Bloch, the author of Effective Java, which can not only avoid the problem of multithreaded synchronization, but also prevent deserialization from recreating new objects, which is a strong barrier. However, I think that as a result of the addition of enum features in 1.5, writing in this way makes people feel rusty.
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;}}
Conclusion: I personally prefer static internal class writing and hungry Chinese writing, in fact, these two writing methods can cope with the vast majority of situations. Other writing methods can also be chosen, mainly depending on the business needs.
Observer mode
An one-to-many dependency between objects. When the state of an object changes, all objects that depend on it are notified and updated automatically.
Observer mode UML diagram
People who can't read the picture come here with a small bench and give you a chestnut: suppose there are three people, Xiaomei (female, 28), Lao Wang and Lao Li. Xiao Mei is very beautiful and coquettish. Lao Wang and Lao Li are two middle-aged male losers who keep an eye on Xiaomei's every move. One day, Xiaomei said: my husband is not at home today, a person is so bored, this sentence was heard by Lao Wang and Lao Li, as a result, he was overjoyed and rubbed. After a while, Lao Wang rushed to Xiaomei's door, so he entered the door. .. Here, Xiaomei is the observer, Lao Wang and Lao Li are the observers, and the observers send a message, and then the observers deal with it accordingly and look at the code:
Public interface Person {/ / Lao Wang and Lao Li can receive the message void getMessage (String s) from Xiao Mei through this interface.
This interface is equivalent to the phone numbers of Lao Wang and Lao Li. When Xiaomei sends a notice, she will call getMessage. To make a call is to call the interface. It doesn't matter if you don't understand. Read on first.
Public class LaoWang implements Person {private String name = "Lao Wang"; public LaoWang () {} @ Override public void getMessage (String s) {System.out.println (name + ") received a call from Xiaomei saying:" + s);}} public class LaoLi implements Person {private String name = "Lao Li" Public LaoLi () {} @ Override public void getMessage (String s) {System.out.println (name + "received a call from Xiaomei:->" + s);}}
The code is simple. Let's take a look at Xiaomei's code:
Public class XiaoMei {List list = new ArrayList (); public XiaoMei () {} public void addPerson (Person person) {list.add (person) Traverse the list and send your notice to all those who have a crush on you, public void notifyPerson () {for (Person person:list) {person.getMessage ("I'm the only one in the family today, come over, whoever comes first will get me!");}
Let's write a test class to see if the results are correct.
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 both registered xiao_mei.addPerson (lao_wang) with Xiaomei. Xiao_mei.addPerson (lao_li); / / Xiaomei sends notification xiao_mei.notifyPerson () to Lao Wang and Lao Li;}}
I took a screenshot of the running result.
Running result
Perfect ~ ~
Decorator mode
The existing business logic is further encapsulated to add additional functions, such as the IO stream in Java uses the decorator mode, and users can assemble it at will to achieve the desired effect. For example, chestnut, I want to eat a sandwich. First of all, I need a big sausage. I like cream. I add a little cream to the sausage, then put some vegetables on it, and finally, I clip it with two slices of bread. It's a big lunch, nutritious and healthy. (ps: do not know where to sell delicious sandwiches in Shanghai, ask for recommendation ~) then how should we write the code? First, we need to write a Food class that all other foods inherit. 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;};}
The code is simple, so I won't explain it, and then we'll write a few 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 () + "+ cream";}} / / vegetable 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 () + "+ vegetables";}}
These classes are all similar. Pass in a parameter of type Food in the constructor, and then add some logic to the make method. If you still don't understand why it is written in this way, there is no hurry. Take a look at how my Test class is written, and you will understand it.
Public class Test {public static void main (String [] args) {Food food = new Bread (new Vegetable (new Cream (new Food (sausage); System.out.println (food.make ());}}
See, layer by layer of packaging, we look from the inside out: inside I new a sausage, I wrap a layer of cream on the outside of the sausage, I add a layer of vegetables on the outside of the cream, and what I put on the outside is bread, isn't it very vivid? . This design pattern is almost the same as in real life. Do you understand? Let's take a look at the running results.
Running result
A sandwich will be ready.
Adapter mode
Connect two completely different things together, just like a transformer in real life. Suppose a mobile phone charger needs a voltage of 20V, but the normal voltage is 220V, then a transformer is needed to convert the 220V voltage into 20V voltage. In this way, the transformer connects the 20V voltage with the mobile phone.
Public class Test {public static void main (String [] args) {Phone phone = new Phone (); VoltageAdapter adapter = new VoltageAdapter (); phone.setAdapter (adapter); phone.charge ();}} / / Mobile class Phone {public static final int V = 220 / / normal voltage 220v, which is a constant private VoltageAdapter adapter; / / charging public void charge () {adapter.changeVoltage ();} public void setAdapter (VoltageAdapter adapter) {this.adapter = adapter }} / / Transformer class VoltageAdapter {/ / function of changing voltage public void changeVoltage () {System.out.println ("charging..."); System.out.println ("original voltage:" + Phone.V + "V") System.out.println ("Voltage after transformer conversion:" + (Phone.V-200) + "V");}}
Factory model
Simple factory pattern: an abstract interface, an implementation class of multiple abstract interfaces, a factory class, used to instantiate an 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 starts to start") ;} public void stop () {System.out.println ("Benz stopped.") ;} class Ford implements Car {public void run () {System.out.println ("Ford starts to start.") ;} public void stop () {System.out.println ("Ford stopped...") ;}} / / 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 build this kind of car.") ;}
Factory method pattern: there are four roles, abstract factory pattern, concrete factory pattern, abstract product pattern, concrete product pattern. Instead of instantiating a concrete product by a factory class, it is de-instantiated by a subclass of the abstract factory
/ / Abstract product role public interface Moveable {void run ();} / / specific product role 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 ();}}
Abstract factory pattern: unlike the factory method pattern, the factory in the factory method pattern produces only a single product, while the factory in 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 is abstract class and 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 ();}} Agent Mode (proxy)
There are two kinds, static proxy and dynamic proxy. First of all, let's talk about static agents. I don't talk about many theoretical things. Even if I do, you won't understand. What real role, abstract role, agent role, delegate role. It's a mess. I can't understand it. Before learning the agency mode, I went to the Internet to look through a lot of materials and open a link. Basically, it was all for you to analyze what role there was and a lot of theories. It seemed very laborious. If you don't believe it, you can go and have a look. I just don't understand what they're talking about. Let's not be empty, just use examples from life. (note: I am not denying theoretical knowledge here. I just think that sometimes theoretical knowledge is obscure and difficult to understand. People who like to find fault with it go away. You are here to learn knowledge, not to find fault.) when we reach a certain age, we are going to get married. Getting married is a very troublesome thing (including those who are urged to marry by their parents). Rich families may find the chief ceremony to preside over the wedding, appears lively, foreign style ~ good, now the business of the wedding company has come, we just need to give money, the wedding company will help us arrange a whole set of marriage process. The whole process goes something like this: family urging for marriage-> the day when the families of both men and women agree to get married-> find a reliable wedding company-> hold the wedding ceremony at the agreed time-> how the wedding company plans to arrange the wedding program after the wedding. We have no idea what the wedding company will do after the wedding. no, no, no. Don't worry, it's not a black agent. All we have to do is give the money to others, and they will do things for us. So, the wedding company here is equivalent to the agency role, now you understand what the agent role is. For the code implementation, please see:
/ / Agent interface public interface ProxyInterface {/ / what needs to be represented is marriage. 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 (); / / Agent eating (your own meal, let others eat) / / void eat (); / / Agent shit, let others take a shit / / void shit ();}
Civilized society, agent eating, agent shit and so on I will not write, it is harmful to social morals ~ ~ can understand, let's take a look at the wedding company's code:
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 the wedding company"); System.out.println ("We are preparing for marriage") System.out.println ("rehearsal for the show..."); System.out.println ("Gift purchase..."); System.out.println ("division of labor..."); System.out.println ("you can start getting married"); proxyInterface.marry () System.out.println ("after the marriage, we need to do follow-up processing, you can go home, and our company will do the rest");}}
See, the wedding company needs to do a lot of things, let's take a look at the code of the wedding family:
Public class NormalHome implements ProxyInterface {@ Override public void marry () {System.out.println ("We are married");}}
It is already obvious that married families only need to get married, and wedding companies have to take care of everything. Wedding companies do everything before and after. I heard that wedding companies make a lot of money now. This is the reason. If you do a lot of work, can you not make money? Take a look at the test class code:
Public class Test {public static void main (String [] args) {ProxyInterface proxyInterface = new WeddingCompany (new NormalHome ()); proxyInterface.marry ();}}
The running results are as follows:
At this point, the study of "what are the commonly used web design patterns" is over. I hope to be able to solve your doubts. The collocation of theory and practice can better help you learn, go and try it! If you want to continue to learn more related knowledge, please continue to follow the website, the editor will continue to work hard to bring you more practical articles!
Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.
Views: 251
*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.
Continue with the installation of the previous hadoop.First, install zookooper1. Decompress zookoope
"Every 5-10 years, there's a rare product, a really special, very unusual product that's the most un
© 2024 shulou.com SLNews company. All rights reserved.