1 single-Case mode
Definition: Ensure that a class has only one instance and provides a global access point; Usage scenario: There are some objects we only need one, such as: thread pool, cache, dialog, registry object, log object, etc., if there are multiple problems; compared with global variables: first you have to understand the 1th, The single-case pattern has been so many years that it must have its advantages. On the other hand: using a singleton pattern compared to a global variable, it has the advantage of a global variable, providing a global access point, without the disadvantage of creating a good object at the beginning of a global variable.
Thinking process
- I'm going to create an object: New MyClass ();
- You can only create one: set the access modifier of the construction method to private;
- Can only be created inside the class, use the method to return to the calling class (client), use Myclass.createnewinstance (), and therefore get the method
public static MyClass getNewInstance() { return obj; }
- obj is derived from an instance of Singleton's own definition and is new MyClass (); Because the client is transparent, getnewinstance () can be called and the modifier is private static.
Code
PackageCom.singleton; Public classsingletontest{ Public Static voidMain (string[] args) {Singleton Singleton=singleton.getnewinstance (); System.out.println (Singleton.hashcode ()); Singleton Singleton1=singleton.getnewinstance (); System.out.println (Singleton1.hashcode ()); System.out.println (Singleton==singleton1); }}classsingleton{Private StaticSingleton Singleton =NewSingleton (); PrivateSingleton () {} Public StaticSingleton getnewinstance () {returnSingleton; }}
Description
The singleton pattern also has the ability to put the created object into a method: This can result in more than one object in a multithreaded environment.
Public Static Singleton getnewinstance () { ifnull) { new Singleton (); } return Singleton; }
Policy mode
Definition: Define the algorithm family, separately encapsulated, so that they can replace each other, this pattern is to make the algorithm changes independent of the customer using the algorithm; Design principles: Identify possible changes in the application, separate them, and do not mix with the code that does not need to change; programming for interfaces, not programming for implementations Multi-use combination, less inheritance. Usage Scenario: Simulate duck – add fly () to the duck, rewrite quack (), and more.
Thinking process
- I want to make the operation of the object according to different types and then get different results;
- Defines an interface in which a method exists;
- Write different sub-classes to implement the interface, rewrite the method inside;
- Write environment, where there is a reference to the interface, and write the Get and set method;
- On the client side, create the object of the subclass, create the Environment object, and call the Env.perform () method;
Strategyi.java
Package Com.strategy; Public Interface strategyi{ publicint calc (intint b);}
Addstrategy.java
Package Com.strategy; Public class Implements strategyi{ @Override publicint calc (intint b) { return a + B; }}
Subtractstrategy.java, Multiplystrategy.java, Dividestrategy.java like Environment.java
PackageCom.strategy; Public classenvironment{ PublicStrategyi strategy; PublicEnvironment (Strategyi s) {strategy=s; } PublicStrategyi getstrategy () {returnstrategy; } Public voidSetstrategy (Strategyi s) {strategy=s; } Public voidperform () {System.out.println (Strategy.calc (3, 4)); }}
Client.java
package com.strategy;
public class Client{ public static void main(String[] args) { StrategyI s1 = new AddStrategy(); Environment env1 = new Environment(s1); env1.perform(); StrategyI s2 = new SubtractStrategy(); Environment env2 = new Environment(s2); env2.perform(); env2.setStrategy(s1); env2.perform(); }}
Observer pattern
The Observer pattern defines a one-to-many dependency that allows multiple observers to listen to a Subject object at the same time, and notifies all observer objects when the state of the subject object changes, allowing them to change themselves.
The composition of the Observer pattern
- Abstract theme roles: We generally believe that the principal object is a collection of all the observers, and we generally define the Addobserver,removeobserve in the interface by defining the abstract topic role as an interface;
- Abstract Observer role: We define the interface of an abstract observer before the observer, and define the method that should be used in the interface;
- Specific topic role: Here we define an interface that contains a collection of observers to add or delete;
- Specific observer: The specific observer is used to observe the specific subject role.
Java and observer patterns
A large number of observer patterns are used in the JDK, which provides the observer interface and the observable abstract class , which we generally criticized as the design of the JDK is that it defines the abstract theme role as an abstract class instead of using an interface.
The specific implementation of the observer pattern
Abstract theme Roles
Package Com.observer; Public Interface watched{ publicvoid Addwatcher (Watcher Watcher); Public void Removewatcher (Watcher Watcher); Public void Notifywatcher (String s);}
Abstract Observer pattern
Package Com.observer; Public Interface watcher{ publicvoid update (String s);}
Specific theme Roles
PackageCom.observer;Importjava.util.ArrayList; Public classConcretewatchedImplementswatched{ArrayList<Watcher> list =NewArrayList (); @Override Public voidAddwatcher (Watcher Watcher) {List.add (watcher); } @Override Public voidRemovewatcher (Watcher Watcher) {list.remove (watcher); } @Override Public voidNotifywatcher (String s) { for(Watcher watcher:list) {watcher.update (s); } }}
Specific observer patterns
Package Com.observer; Public Interface watcher{ publicvoid update (String s);}
Using Tests
PackageCom.observer; Public classclient{ Public Static voidMain (string[] args) {concretewatched girl=Newconcretewatched (); Concretewatcher boy1=NewConcretewatcher (); Concretewatcher Boy2=NewConcretewatcher (); Concretewatcher Boy3=NewConcretewatcher (); Girl.addwatcher (boy1); Girl.addwatcher (BOY2); Girl.addwatcher (BOY3); Girl.notifywatcher ("I'm sorry."); Girl.removewatcher (BOY2); Girl.notifywatcher ("Happy"); }}
Decorator mode
Decorator mode dynamically attaches responsibility to objects, and to extend functionality, adorners provide more resilient alternative files than inheritance
Design principles
Open for extension, close for modification
Features of decorator mode
- The decorator is an alternative to the inheritance relationship by extending the function of the object in a transparent manner to the client;
- Decorator mode dynamically adds more responsibility to the object in a transparent way, in other words, the client will no longer be decorated before or after the decoration changes;
- Decorator mode expands the functionality of an object in such a way that it does not need to create more subclasses.
- Decorator Mode delegate the client's call to the decorated class, the key to the decoration mode is that the expansion is completely transparent;
- Decorative mode is the ability to dynamically extend an object without changing the original class file and inheritance, by creating an ornamental class object.
- The adornment object has the same interface as the real object; The Adornment object contains a reference to an abstract interface; The adornment object receives the request and then sends the request to the true object; The Adornment object can add some additional functionality before or after forwarding these requests .
Decoration Mode and inheritance
- Used to extend the functionality of specific objects, without subclasses, dynamic, assigning responsibilities at run time, more flexible;
- The ability to extend a class of objects requires subclasses, static, assigning responsibilities at compile time, but leads to more subclasses and less flexibility.
Composition
- Abstract build role: An abstract interface is given to regulate the objects that are prepared to accept additional responsibilities:
Package Com.decorator; Public Interface component{ publicvoid saysomething ();}
- Concrete Build role: Define a Class (decorator) that will receive additional responsibilities:
Package Com.decorator; Public class Implements component{ @Override publicvoid saysomething () { System.out.println ("Concretecompoent is running");} }
- Decorative role: A reference to an abstract build role, and implements an interface that is consistent with the abstract interface:
Package Com.decorator; Public class Implements component{ public Component Component; @Override publicvoid saysomething () { component.saysomething (); } Public void dothing () { System.out.println ("Decorator haha");} }
- Specific decorative role: responsible for adding additional responsibilities to the Component Object (decorator):
PackageCom.decorator; Public classConcretedecoratorextendsdecorator{ PublicComponent Component; Publicconcretedecorator (Component Component) { This. Component =component; } @Override Public voidsaysomething () {component.saysomething (); This. dothing (); } Public voiddothing () {System.out.println ("Concretedecorator haha"); }}
Package Com.decorator; Public class client{ publicstaticvoid main (string[] args) { New ConcreteDecorator2 ( new Concretedecorator (new concretecompoent ())); Component.saysomething (); }}
Design mode blink