For the original article, see www. ucai. cnblogdetail7023? Mid1 & amp; f12 can be run online to view the effect! & Amp; lt; followed by the previous article & amp; gt; 7. ChainofResponsibility:... 7. Chainof Responsibility ):
Multiple objects have the opportunity to process requests and decouple the request sender and receiver. Like a cash machine in a bank, no matter which one can get the money.
Benefit: The object hidden chain structure is simplified to facilitate the addition of new duty nodes.
Disadvantage: The request may have no receiver or be called by multiple receivers, reducing the performance.
Application scenario: process multiple requests.
Code implementation:
_ Handler = $ handler;} protected function _ success ($ request) {output (sprintf ("% s's request was passed", $ request-> getName ())); return true;} abstract function handleRequest ($ request);}/*** ConcreteHandler: President: processes the requests it is in charge of and can access the successor, if the request can be processed, it will be processed; otherwise, the request will be forwarded to its successor. **/Class ConcreteHandlerLeader extends Handler {function _ construct ($ handlerName) {$ this-> _ handlerName = $ handlerName;} public function handleRequest ($ request) {if ($ request-> getDay () <0.5) {output (sprintf ('% s was told', $ this-> _ handlerName )); // you have already greeted leader with return $ this-> _ success ($ request);} if ($ this-> _ handler instanceof Handler) {return $ this-> _ handler-> handleRequest ($ request) ;}}/ *** Manager **/class ConcreteHandlerManager extends Handler {function _ construct ($ handlerName) {$ this-> _ handlerName = $ handlerName;} public function handleRequest ($ request) {if (0.5 <= $ request-> getDay () & $ request-> getDay () <= 3) {output (sprintf ('% s signed', $ this-> _ handlerName )); // the department manager signs return $ this-> _ success ($ request);} if ($ this-> _ handler instanceof Handler) {return $ this-> _ handler-> handleRequest ($ request) ;}} class ConcreteHandlerGeneralManager extends Handler {function _ construct ($ handlerName) {$ this-> _ handlerName = $ handlerName;} public function handleRequest ($ request) {if (3 <$ request-> getDay () & $ request-> getDay () <10) {output (sprintf ('% s signe', $ this-> _ handlerName); // return $ this-> _ success ($ request );} if ($ this-> _ handler instanceof Handler) {return $ this-> _ handler-> handleRequest ($ request );} else {output (sprintf ('No one can approve request more than 10 days ') ;}}/*** leave application ***/class Request {private $ _ name; private $ _ day; private $ _ reason; function _ construct ($ name = '', $ day = 0, $ reason = '') {$ this-> _ name = $ name; $ this-> _ day = $ day; $ this-> _ reason = $ reason;} public function setName ($ name) {$ this-> _ name = $ name;} public function getName () {return $ this-> _ name;} public function setDay ($ day) {$ this-> _ day = $ day;} public function getDay () {return $ this-> _ day;} public function setReason ($ reason) {$ this-> _ reason = $ reason;} public function getReason () {return $ this-> _ reason ;}} class Client {public static function test () {$ leader = new ConcreteHandlerLeader ('Leader '); $ manager = new ConcreteHandlerManager ('manager'); $ generalManager = new ConcreteHandlerGeneralManager ('generalmanager '); // request instance $ Request = new request ('ucai', 4, 'stopped'); $ leader-> setSuccessor ($ manager ); $ manager-> setSuccessor ($ generalManager); $ result = $ leader-> handleRequest ($ request) ;}} Client: test ();
8. Strategy ):
Define a series of algorithms, encapsulate each algorithm, and make them replaceable. Like players on the basketball team, on-and off-court players. The coach can let the team go down or go on the court.
Benefit: defines a series of reusable algorithms and behaviors, and eliminates if else statements.
Disadvantage: the caller must know all the policy classes.
Application scenario: used to replace objects.
Code implementation:
OnTheWay () ;}} class Client {public static function test () {$ travel = new Context (); $ travel-> find (new faster strategy ()); $ travel-> find (new RideBickStrategy (); $ travel-> find (new CarStrategy () ;}} Client: test ();
Known mode
1. Memento ):
The state of the object at a time point. Do you still remember him at the same table "my teacher is here?
Benefit: provides users with a recovery mechanism.
Disadvantage: resource consumption.
Application scenario: used for data to be saved.
Code implementation:
_ State = '';} public function createMemento () {// Create a memorandum return new Memento ($ this-> _ state);} public function restoremento (Memento $ memento) {// restore the initiator to the state recorded by the memorandum object $ this-> _ state = $ memento-> getState ();} public function setState ($ state) {$ this-> _ state = $ state;} public function getState () {return $ this-> _ state;} public function showState () {output ($ this-> _ state);} class Memento {// memorandum (M Emento) role private $ _ state; public function _ construct ($ state) {$ this-> setState ($ state);} public function getState () {return $ this-> _ state;} public function setState ($ state) {$ this-> _ state = $ state ;}} class Caretaker {// Caretaker) role private $ _ memento; public function getMemento () {return $ this-> _ memento;} public function setMemento (Memento $ memento) {$ this-> _ memento = $ memento;} clas S Client {public static function test () {$ org = new Originator (); $ org-> setState ('open'); $ org-> showState (); /* Create a memo */$ memento = $ org-> createMemento ();/* save the memo through Caretaker */$ caretaker = new Caretaker (); $ caretaker-> setMemento ($ memento);/* change the status of the target object */$ org-> setState ('close'); $ org-> showState (); /* restore operation */$ org-> restoreMemento ($ caretaker-> getMemento (); $ org-> showState () ;}} Client: test (); Return; try {$ db-> beginTransaction (); $ succ = $ db-> exec ($ SQL _1); if (! $ Succ) {throw new Exception ('SQL 1 update failed');} $ succ = $ db-> exec ($ SQL _2); if (! $ Succ) {throw new Exception ('SQL 2 update failed');} $ succ = $ db-> exec ($ SQL _3); if (! $ Succ) {throw new Exception ('SQL 3 update failed');} $ db-> commit ();} catch (Exception $ exp) {$ db-> rollBack ();}
Deep mode
1. Interpreter mode (Interpreter ):
Defines the grammar of a language and creates an interpreter to explain the sentences in the language. Everyone who has used the dictionary knows how to use it.
Benefits: high scalability and flexibility.
Disadvantage: it may be difficult to maintain complex grammar.
Application scenario: used for pairing or one-to-many requests.
2. Visitor mode (Visitor ):
Encapsulate some operations that act on each element in a data structure. you can define new operations that act on these elements without changing the data structure. Such as a bank number generator.
Benefit: concentrate related things into a visitor object.
Disadvantage: it is difficult to add new data structures.
Application scenarios: queuing and queuing.
III. Summary
This article introduces the behavior pattern, which involves the assignment between algorithms and objects. the behavior pattern uses the inheritance mechanism to distribute behavior between classes, and TemplateMethod and Interpreter are class behavior patterns. Behavior object mode uses object combination instead of inheritance. some behavior object modes describe how a group of peer-to-peer objects collaborate to complete tasks that cannot be completed by any of the objects separately, for example, Mediator introduces a mediator object between objects to provide the indirect property required for loose coupling. Chain of Responsibility provides more loose coupling, it implicitly sends a loose request to an object through a candidate object chain, and determines which candidates participate in the chain at the runtime. The Observer defines and maintains the dependency between objects; other behavior object modes often encapsulate the behavior in an object and assign the request to it. The Strategy mode encapsulates the algorithm in the object, in this way, you can change and specify the algorithm used by an object. the Command mode encapsulates the request in the object so that it can be passed as a parameter, it can be stored in the history list or used in other ways; State mode encapsulates the State of an object, so that when the State object of this object changes, this object can change its behavior; the Visitor mode encapsulates the behavior distributed among multiple classes. The terator mode abstracts the methods for accessing and traversing objects in a collection.