Thứ Ba, 11 tháng 8, 2015

Design Patterns: The Facade Pattern - part 2

Problem
Let's assume that you have a few operations to be made in sequence, and that the same action is required in multiple places within your application. You have to place the same code again and again in different places. You have done that, but after a few days you find that something needs to be changed in that code.

Do you see the problem? We have to introduce the changes in all of the places that the code exists. It's painful, isn't it?

Solution
As a solution, what you should be doing is to create a lead controller, which handles all of the repeating code. From the calling point of view, we will just call the lead controller to perform actions based on the parameters provided.

Now if we need to introduce any change in the process, then we will just need to change the lead controller instead of making the change in all places where we used that code.

Example
In this tutorial, let's choose one lesson so that it makes things more readable. Let's say that you have been given a task to plan your friend's marriage. If you do everything on your own, then imagine the things you need to cover. It will create a higher possibility for error, and increase the chance of missing something that can drastically affect your friend's wedding.

In this case, instead of doing everything on your own, you should use a wedding planner and make sure the job gets done in a well-managed manner with less chance of a mistake.

Here, you are behaving as a client who initiates the process, and the wedding planner is working as a "facade" for you, completing the job based on your direction.

Code Example

In this section we will see one more example, which is very common for websites, of course with a code example. We will see an implementation of the facade design pattern using a product checkout process. But before checking perfect code with the facade pattern, let's have a look at some code that has a problem.

A simple checkout process includes the following steps:

Add product to cart.
Calculate shipping charge.
Calculate discount.
Generate order.



Share

& Comment

0 nhận xét:

Đăng nhận xét

 

Copyright © 2015 PHP Scripts - PHP Sources Libraries

Designed by Templateism | Thiết kế website