In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-03-31 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >
Share
Shulou(Shulou.com)06/03 Report--
This article mainly explains "how to use structural pattern". The content of the explanation in this article is simple and clear, and it is easy to learn and understand. Please follow the editor's train of thought. Let's study and learn "how to use structural mode"!
Adapter mode
The so-called adapter pattern is to transform the structure of one class into the interface of another class. Makes it possible for classes that can't work because of interface incompatibility to work together.
It is more common in life that when we want to connect the monitor, the vga needs to be converted to hdmi, and the power supply adapts. For example, we may need a 220v charging head, but only a 110v charging head, so we need to adapt the 220v charging head to a 110v charging head.
Adaptee: code that needs to be adapted, old interface
Adapter: adapter class that forwards calls to Adaptee
Target: new interfaces supported
Adapter mode UML
Class adapter pattern
Target
Public interface Target {void output110v ();}
Adaptee
Public class Adaptee {public void output220v () {System.out.println (output voltage);}}
Adapter
Public class Adapter extends Adaptee implements Target {@ Override public void output110v () {this.output220v ();}}
It should be noted that Adapter inherits the source class and implements the target class.
Client
Public class Client {public static void main (String [] args) {Target target = new Adapter (); target.output110v ();}}
Although we use the charging head of output110v, after Adapter, we finally call the charging head of output220v through this.output220v (), which adapts the output220v to output110v.
Object adapter pattern
In fact, it is different to say that Adaptor is implemented in a different way. The class adapter pattern inherits the source class (that is, the class that needs to be adapted) to achieve the target class.
There is a problem when we need to adapt to multiple classes, because multiple interfaces are allowed to be implemented in java, but only one class can be inherited.
To solve this problem, we can take the class that needs to be adapted as the member variable of Adapter, and then adapt it through the constructor.
Public class NewAdapter implements Target {Adaptee adaptee; public NewAdapter (Adaptee adaptee) {this.adaptee = adaptee;} @ Override public void output110v () {adaptee.output220v ();}} proxy mode
Agent mode is also one of the more commonly used design patterns, we contact the most spring aop, is the use of dynamic agent mode to complete. The agent mode can be divided into ordinary agent mode, compulsory agent mode and dynamic agent mode, which is also emphasized in this paper, of course, there is also its agent mode.
First, use a piece of code to understand the agent mode, the scene is the player playing the game.
Subject: common interface, existing interface used by clients
RealSubject: classes of real objects
ProxySubject: proxy object class
Proxy mode UML
General agent mode
Through the above example, I believe we all feel a little bit about the agent mode, but it does not seem to be so appropriate. The above test category still needs to create a new player, which is equivalent to what we log in to the game on our mobile phone, and then give the phone to the trainer for practice. In fact, it is often possible to practice the account password.
This leads to the general agent mode, the client can not access the real role, can only access the agent role, we can know the existence of the agent.
Subject
Public interface SubjectNormalGamePlayer {public void login (); public void upgrade (); public void matches ();}
RealSubject
Public class RealSubjectNormalPlayerImpl implements SubjectNormalGamePlayer {private String name; private String password; public RealSubjectNormalPlayerImpl (String name, String password) {this.name = name; this.password = password;} @ Override public void login () {if (name.equals ("cutey") & & password.equals ("123456")) {System.out.println (name + "login successful") } @ Override public void upgrade () {System.out.println (name + "upgrade");} @ Override public void matches () {System.out.println (name + "qualifying");}}
ProxySubject
Public class ProxySubjectNormalPlayerImpl implements SubjectNormalGamePlayer {SubjectNormalGamePlayer gamePlayer; / / pay attention to the difference here. We use our account and password to log in to the real character / / We do not directly use the real character's phone to call public ProxySubjectNormalPlayerImpl (String name, String password) {gamePlayer = new RealSubjectNormalPlayerImpl (name, password);} @ Override public void login () {System.out.print ("practice:"); gamePlayer.login () } @ Override public void upgrade () {System.out.print ("substitute:"); gamePlayer.upgrade ();} @ Override public void matches () {System.out.print ("substitute:"); gamePlayer.matches ();}}
Client
Public class Client {public static void main (String [] args) {/ / pass the test class is also very different, it is not necessary to show the construction of the real role class SubjectNormalGamePlayer proxy = new ProxySubjectNormalPlayerImpl ("cutey", "123456"); proxy.login (); proxy.upgrade (); proxy.matches ();}} mandatory proxy
The ordinary agent, uh, is to find an agent object to help fight, but the compulsory agent is mainly reflected in "coercion". The role class will specify an agent, and agents found in other ways cannot play for me. You must use the agent I specify.
Subject
Like most code in the normal proxy model, the difference is that a mandatory proxy object is added.
Public interface SubjectForceGamePlayer {/ / omit login, upgrade and ranking methods / / force the proxy object public SubjectForceGamePlayer getForceProxy ();}
RealSubject
Public class ForceGamePlayerImpl implements IForceGamePlayer {private String name; private String password; private IForceGamePlayer proxy = null; / / specify who needs to proxy public ForceGamePlayerImpl (String name, String password) {this.name = name; this.password = password;} @ Override public IForceGamePlayer getForceProxy () {/ / force the proxy class to be specified, and only in this way can proxy be assigned proxy = new ForceProxyGamePlayerImpl (this) Return proxy;} @ Override public void login () {/ / as long as it is not a self-specified proxy, the other proxy must be null if (proxy! = null) {if (name.equals ("imperfect") & & password.equals ("123456")) {System.out.println (name + "login success") }} else {System.out.println ("proxy required");} @ Override public void upgrade () {if (proxy! = null) {System.out.println (name + "upgrade");} else {System.out.println ("proxy required") } @ Override public void matches () {if (proxy! = null) {System.out.println (name + "qualifying");} else {System.out.println ("need an agent");}
ProxySubject
Public class ProxySubjectForcePlayerImpl implements SubjectForceGamePlayer {private SubjectForceGamePlayer gamePlayer; / / receives the specified public ProxySubjectForcePlayerImpl (SubjectForceGamePlayer gamePlayer) {this.gamePlayer = gamePlayer;} / / omits the login, upgrade and match methods of the proxy object / / does not have a proxy object, and temporarily returns itself @ Override public SubjectForceGamePlayer getForceProxy () {return this;}}
Client
Public class Client {public static void main (String [] args) {wrongProxy1 (); wrongProxy2 (); correctProxy ();} public static void correctProxy () {SubjectForceGamePlayer player = new RealSubjectForcePlayerImpl ("cutey", "123456"); / / your agent must be specified by me and SubjectForceGamePlayer proxy = player.getForceProxy (); proxy.login () Proxy.upgrade (); proxy.matches ();} public static void wrongProxy1 () {SubjectForceGamePlayer player = new RealSubjectForcePlayerImpl ("cutey", "123456"); SubjectForceGamePlayer proxy = new ProxySubjectForcePlayerImpl (player); proxy.login (); proxy.upgrade (); proxy.matches ();} public static void wrongProxy2 () {SubjectForceGamePlayer player = new RealSubjectForcePlayerImpl ("cutey", "123456") Player.login (); player.upgrade (); player.matches ();}} dynamic proxy
This should be used more in the agency model, and I think it is most necessary for all of you to understand and master it. The so-called dynamic proxy refers to the method that gets the proxied object and executes the proxy at run time instead of specifying who the agent is in the compiler.
The following example is using the InvocationHandler and Proxy classes provided in jdk
Subject and RealSubject are all the same as ordinary agent mode.
ProxySubject
We don't know who to proxy for, so we need to inherit the InvocationHandler class
Public class ProxySubjectDynamicPlayerImpl implements InvocationHandler {Class cls = null; / / classes to be proxied Object obj = null; / / objects that need proxies / / specify objects that need proxies public ProxySubjectDynamicPlayerImpl (Object obj) {this.obj = obj } @ Override public Object invoke (Object proxy, Method method, Object [] args) throws Throwable {/ / call the proxy object's method Object result = method.invoke (this.obj, args); if (method.getName (). EqualsIgnoreCase ("login") {System.out.println ("remote login reminder: someone has logged in to my account");} return result;}}
Client
Public class Client {public static void main (String [] args) {SubjectDynamicPlayer player = new RealSubjectDynamicPlayerImpl ("imperfect", "123456"); / / send the information that needs to be proxied to handler, remember the invoke method / / the proxied object method InvocationHandler handler = new ProxySubjectDynamicPlayerImpl (player) has been implemented in the invoke method / / get the class loading attribute ClassLoader cl = player.getClass (). GetClassLoader () of the proxy class; / / get the interface Class [] interfaces = player.getClass (). GetInterfaces () of the proxy class; / / give the above three information to Proxy to create a proxy class SubjectDynamicPlayer proxy = (SubjectDynamicPlayer) Proxy.newProxyInstance (cl, interfaces, handler); proxy.login () Proxy.upgrade (); proxy.matches ();}}
At compile time, we have no idea who to agent for. Everything is known at run time. This is called "dynamic".
Decoration mode
The decoration pattern is the responsibility of dynamically adding some love to an object, and in terms of adding functionality, the decoration pattern is more flexible than generating subclasses.
No matter what you do, the most important thing is to give full play to your strengths and avoid your weaknesses, and the same is true for selling mobile phones. You must introduce the selling points in detail, but do not mention the shortcomings.
Component: define the interface of an object to which you can dynamically add responsibilities
ConcreteComponent: specific object
Decorator: decorates abstract classes, inherits Component, and extends Component from outer classes
ConcentrateDecorator: specific decoration class
Decoration mode UML
Decoration mode
Component
Public abstract class ComponentMobile {/ / Product name private String name; / / omit the get,set,tostring method public abstract void showDetails (); public abstract void onSale (String userName);}
Concentrate Component
Public class ConcreteComponentOnePlus extends ComponentMobile {public ConcreteComponentOnePlus (String name) {super (name);} @ Override public void showDetails () {System.out.println ("processor: Snapdragon 888\ r\ nPhoto: Hassel Professional Mode\ r\ nscreen: 2k+120hz flexible screen\ r\ ncharging: 65w Quick charge") @ Override public void onSale (String userName) {System.out.println (userName + "purchased" + getName ());}}
Decorator
Public abstract class Decorator extends ComponentMobile {/ / bring me the phone to be decorated private ComponentMobile mobile; public Decorator (String name, ComponentMobile mobile) {super (name); this.mobile = mobile;} / / the details are still to be shown / / but how to show, the subclass can be modified by public void showDetails () {mobile.showDetails () } / / Mobile phones are also public void onSale (String name) {mobile.onSale (name);}}
Note that the details of our mobile phones still have to be displayed, and we can't say that if we don't do well, we should not say it and deceive consumers. Can recognize you is called makeup, can not recognize you as plastic surgery, we are talking about decoration mode, not plastic surgery mode.
Concrete Decorator
Public class ConcreteDecoratorSystem extends Decorator {public ConcreteDecoratorSystem (String name, ComponentMobile mobile) {super (name, mobile);} / Decoration system public void decorateScreen () {System.out.println ("ColorOS comes out of the factory, other models of mobile phones will also gradually adapt");} @ Override public void showDetails () {/ / want to introduce the system first, then say other parameters decorateScreen () Super.showDetails ();}} public class ConcreteDecoratorPrice extends Decorator {public ConcreteDecoratorPrice (String name, ComponentMobile mobile) {super (name, mobile);} / / published price public void decoratePrice () {System.out.println ("8 + 128 String name 4999"); System.out.println ("8 + 256: 5499");} @ Override public void showDetails () {super.showDetails () / / after introducing others, announce the price with high performance and price decoratePrice ();}}
Client
Public class Client {public static void main (String [] args) {/ / Mobile phone launch, original product ComponentMobile mobile = new ConcreteComponentOnePlus ("OnePlus 9 Pro"); / / Decoration system mobile = new ConcreteDecoratorSystem (mobile.getName (), mobile); / / Decoration price mobile = new ConcreteDecoratorPrice (mobile.getName (), mobile); mobile.showDetails () / / users take a look, ah, not bad, bought mobile.onSale ("cutey");}} Thank you for reading, the above is the content of "how to use structural pattern". After the study of this article, I believe you have a deeper understanding of how to use structural pattern, and the specific use needs to be verified in practice. Here is, the editor will push for you more related knowledge points of the article, welcome to follow!
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: 0
*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.