Design mode Getting Started Guide

Source: Internet
Author: User
Keywords Nbsp; logout US design pattern

Want to know what the design pattern is? In this article, I will explain why design patterns are important. I will also provide some examples of PHP to explain when and where to use design patterns.

What is a design pattern?

Design patterns are an optimized and reusable approach to our day-to-day programming problems. A design pattern is not just a class or a library that can be easily integrated into a system. It is a template that can only be used in the right context. It's not just a language. A good design pattern should be applicable to most languages, but also to the characteristics of the language. Most importantly, any design pattern, if used in the wrong place, could turn into a double-edged sword, which can be disastrous and cause many problems for you. Of course, in the right place, it's your savior.

There are three basic design patterns

-structured Creative behavioral

Structured design patterns typically deal with relationships between entities, making it easier for these entities to http://www.aliyun.com/zixun/aggregation/18521.html "> work together."

Creative design patterns provide an instantiation mechanism that makes it easier to create objects in the right context.

Behavioral design patterns are used for communication between entities, making it easier and more flexible to communicate between these entities.

Why do we use design patterns?

A design pattern is a solution that is carefully considered in accordance with the principles of a procedural problem. Many programmers have encountered these problems and addressed them to the right remedy. If you encounter these problems, why not use the proven methods to recreate one yourself?

Example

Let's imagine that you get a task that merges two different classes of behavior according to the situation. These two classes are heavily applied to different parts of the existing system, which makes it difficult to remove the two classes and change existing code. To make these changes, changing the existing code also tests the changed code, because the system may rely on these changes in different components, which introduces new bugs. Instead, you can implement a variant based on the policy pattern and adapter pattern, and you can easily handle this type of situation.

Class Strategyandadapterexampleclass {private $_class_one; private $_class_two; private $_context; public Function __ Construct ($context) {$this->_context = $context;} public Function Operation1 () {if ($this->_context = = "Context_ For_class_one ") {$this->_class_one->operation1_in_class_one_context ();} else ($this->_context = =" Context_ For_class_two ") {$this->_class_two->operation1_in_class_two_context ();}} }


It's easy. Now we can take a closer look at the policy model.

Policy mode


In the example above, the strategy used is to determine the value of the $context variable based on the initialization of the class. If the context value is Class_one, Class_one is used or class_two is used.

Smart, but where can I use it?


Imagine that you are now designing a class that can update or create a new user record. It still requires the same input (name, address, mobile number, and so on), but, depending on the given situation, a different approach is required when updating or creating. Now, you may be using just one else to do this. But what if you need this class in a different place? In this case, you will have to rewrite the same else statement over and over again. Isn't it easier to use policy patterns in this context?

Class User {public Function createorupdate ($name, $address, $mobile, $userid = null) {if (Is_null ($userid)) {//it means the User doesn't ' t exist verb, create a new record} else {//It means the user already exists, ethically update based on the given UserID}} }


Now, the usual policy pattern involves encapsulating your algorithm in another class, but in this case creating another class might be wasteful. Remember that you don't have to use this template. Using this change in a similar situation can solve the problem.
Adapter mode

This also allows you to change some of the input received from the client class to match the functionality of the adapter.

How can I use it?

Another term for describing an adapter class is encapsulation, which allows you to encapsulate the behavior into a class and reuse it in the right circumstances. As a classic example, when you create a domain class for a table, you can use an adapter class to encapsulate all the methods into a method, rather than calling different tables and using them one by one. This not only allows you to reuse any behavior you want to use, but also allows you to rewrite the code if you need to use the same behavior in different places.

Comparing two implementations,

Non-Adapter method

$user = new User (); $user->createorupdate (//inputs); $profile = new profile (); $profile->createorupdate (//inputs);


If we need to do this in different places, or even reuse it in different projects, we'll have to write this down again.

better.

Instead we can do this:

$account _domain = new account (); $account _domain->newaccount (//inputs);


In this case, we have an encapsulated class as our account class:

class account () {Public Function NewAccount (//inputs) {$user = new user (); $user->createorupdate (//subset of inputs); $profile = new profile (); $profile->createorupdate (//subset of inputs); } }


This way, you can use it whenever you need an account class. In addition, you can encapsulate other classes in the domain class.

Factory method Mode

The main goal of this pattern is to encapsulate the creation process of different classes into a single method. It can return the correct object by providing the correct context for the factory method.

When can I use it?

The best time to use the factory method pattern is when you have various different independent entities. For example, you have a button class that has many different variants, such as Picture buttons, input buttons, and Flash buttons. Depending on your needs, you may want to create a different button-this is where you can use the factory to create a button for you.

Abstract class Button {protected $_html public function gethtml () {return $this->_html;}} class ImageButton extends button {protected $_html = "..."; This should is whatever HTML you want for your image-based button} class Inputbutton extends button {protected $_html = "..."; This should is whatever HTML for your want for your normal button (); Class Flashbutton extends button {protected $_html = "..."; This should is whatever HTML you want for your flash-based button}


Now we can create our factory class:

Class Buttonfactory {public static function Createbutton ($type) {$baseClass = ' Button '; $targetClass = Ucfirst ($type). $ BaseClass; if (class_exists ($targetClass) && is_subclass_of ($targetClass, $baseClass)) {return new $targetClass;} else { throw new Exception ("the button type ' $type ' is not recognized."); } } }


We can use this code like this:

$buttons = Array (' image ', ' input ', ' flash '); foreach ($buttons as $b) {echo Buttonfactory::createbutton ($b)->gethtml ()}


The output should be all HTML button types. This way, you will be able to explain which button to create and reuse these conditions as appropriate.

Decorator mode

The goal of the decorator pattern is that the extended functionality can be applied to a particular instance, and can create an original instance that does not have the extended functionality. The adorner pattern allows you to use more than one adorner class for an instance, so you don't have to dwell on creating a decorator class for each instance. This pattern is optional when inheriting, which refers to the ability to inherit from a parent class. Unlike inheritance, which adds behavior at compile time, decoration allows you to add a new behavior at run time.

We can implement the decorator pattern according to the following steps:

1. Create an adorner class to inherit the original component.

2. In the adorner class, add a component field.

3. Initialize this component in the constructor of the adorner class.

4. In the Decorator class, all the methods that invoke the new component are reset.

5. In the Decorator class, override all component methods that need to change behavior.

When should I use it?

When you have an entity, the entity has new behavior only when the environment needs it, and that's where the decorator pattern is used. For example, you have an HTML connection element, an exit connection, and you want to do something slightly different based on the current page. In order to achieve that goal, we can use the decorator pattern.

First, we need to build different packages as needed.

1. If it's on the home page and it's already logged in, we want this connection to be

tags are packaged.

2. If we are on a different page and have logged in, we want this connection to be encapsulated by the underline tag.

3. If we log in, we want this connection font to be bold.

Once we've built our encapsulation class, we can start writing.




Class Htmllinks {//some methods abound is available to all HTML links} class Logoutlink extends Htmllinks {protected $_html; Public Function __construct () {$this->_html = ' Logout ';} public Function sethtml ($html) {$this->_html = $html;} Public function render () {Echo $this->_html;}} Class Logoutlinkh2decorator extends Htmllinks {protected $_logout_link; public function __construct ($logout _link) {$ This->_logout_link = $logout _link; $this->sethtml ("


” . $this->_html. “

“);

The Public Function __call ($name, $args) {$this->_logout_link-> $name ($args [0]);} Class Logoutlinkunderlinedecorator extends Htmllinks {protected $_logout_link; public Function __construct ($logout _ Link) {$this->_logout_link = $logout _link; $this->sethtml ("". $this->_html. ““); } Public Function __call ($name, $args) {$this->_logout_link-> $name ($args [0]);} Class Logoutlinkstrongdecorator extends Htmllinks {protected $_logout_link; public function __construct ($logout _link) { $this->_logout_link = $logout _link; $this->sethtml ("". $this->_html. “”); } Public Function __call ($name, $args) {$this->_logout_link-> $name ($args [0]);}


We can use them like this:

$logout _link = new Logoutlink (); if ($is _logged_in) {$logout _link = new Logoutlinkstrongdecorator ($logout _link);} if ($in _home_page) {$logout _link = new Logoutlinkh2decorator ($logout _link); else {$logout _link = new Logoutlinkunderlinedecorator ($logout _link);} $logout _link->render ();


Here we can see how we combine multiple decorator classes when we need them. Since all the decorator classes use the __call method, we can still invoke the original method. If we assume that we are now on the home page and have logged in, the HTML output should be:

<strong><h2><a href= "logout.php" >Logouta>h2>strong>


Single-piece mode


Because a single item variable is the same for all calls, this makes it easier for other objects to use a single instance.

When should I use it?


If you need to pass a particular instance from one class to another, you can use a single piece pattern to avoid having to pass this instance through a constructor or parameter. Imagine that you have created a session class that mimics the $_session global array. Since this class only needs to be instantiated once, we can implement a single piece pattern like this:

PHP class Session {private static $instance, public static function getinstance () {if Is_null (self:: $instance)) {self::$ Instance = new self (); Return self:: $instance; Private Function __construct () {} private Function __clone () {}//Any other sessions methods we might use ...} Get a Session instance $session = Session::getinstance ();


By doing so, we can access our session classes in different parts of the code, even in different classes. This class will exist in all call getinstance methods.

Conclusion

In fact, there are more design patterns to learn; In this article, I'll just list some of the famous patterns that I use in my programming process. If you are interested in other design patterns, Wikipedia's design pattern page has enough information. If that's not enough, you can see design patterns: Reusable object-oriented software Basics, which is one of the best design pattern books.

Finally: When you use these design patterns, be sure to be clear that you are solving the correct problem. As I mentioned earlier, these design patterns are a double-edged sword: if used in the wrong environment, they can make things worse: but they are essential if they are used correctly.

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.