TungNT (Blue)

tungnt.blue@gmail.com

User Tools

Site Tools


development:software-architecture:design-patterns:factory

Differences

This shows you the differences between two versions of the page.

Link to this comparison view

Both sides previous revisionPrevious revision
Next revision
Previous revision
development:software-architecture:design-patterns:factory [2024/08/14 13:43] tungntdevelopment:software-architecture:design-patterns:factory [2024/08/19 09:29] (current) tungnt
Line 1: Line 1:
 ====== Factory ====== ====== Factory ======
 +
 +Trong số những kiểu mẫu thiết kế hay design pattern trong PHP thì Factory là một trong những pattern được sử dụng phổ biến nhất.
 +
 +===== Simple Factory Pattern =====
 +
 +**Cách code khi không dùng Factory Pattern:**
 +
 +<file php>
 +//...    
 +
 +    private function getServiceLogistics($cargoVolume)
 +    {
 +        switch ($cargoVolume) {
 +            case 10:
 +                return [
 +                    'name' => 'Truck 10',
 +                    'door' => 6,
 +                    'price' => 250000,
 +                ];
 +            case 20:
 +                return [
 +                    'name' => 'Truck 20',
 +                    'door' => 16,
 +                    'price' => 1500000,
 +                ];            
 +            default:
 +                return [];
 +        }
 +    }
 +    
 +//...    
 +
 +var_dump($this->getServiceLogistics(10));
 +</file>    
 +
 +**Cách code khi dùng Simple Factory Pattern:**
 +
 +<file php>
 +/**
 + * ServiceLogistics
 + */
 +class ServiceLogistics{
 +    private $name;
 +    private $door;
 +    private $price;
 +    
 +    /**
 +     * __construct
 +     *
 +     * @param  mixed $name
 +     * @param  mixed $door
 +     * @param  mixed $price
 +     * @return void
 +     */
 +    public function __construct($name = "Truck 10", $door = 6, $price = 250000) {
 +        $this->name = $name;
 +        $this->door = $door;
 +        $this->price = $price;
 +    }
 +    
 +    /**
 +     * getTransport
 +     *
 +     * @param  mixed $cargoVolume
 +     * @return void
 +     
 +     * Đã chuyển logic thành các class thực thi, tuy nhiên khó mở rộng được do function getTransport ngày càng phình to
 +     * Mong muốn khi thêm một loại mới mà không cần cập nhật lại function getTransport -> sử dụng Method Factory Pattern
 +     */
 +    public static function getTransport($cargoVolume)
 +    {
 +        switch ($cargoVolume) {
 +            case 10:
 +                return new ServiceLogistics();
 +            case 20:    
 +                return new ServiceLogistics('Truck 20', 16, 1500000);    
 +            default:
 +                return [];
 +        }
 +    }
 +}
 +
 +var_dump(ServiceLogistics::getTransport(20));
 +
 +</file>
 +
 +**Ví dụ khác:**
 +
 +<file php>
 +class XMLParser {
 +    function __construct($filePath) {
 +        file_get_content($filePath);
 +    }
 +}
 +
 +class JSONParser {
 +    function __construct($filePath) {
 +        file_get_content($filePath);
 +    }
 +}
 +
 +abstract class ParserFactory {
 +    public static function __construct($param) {
 +         if ($param['type'] = 'XML') {
 +                return new XMLParser($param["filePath"]);
 +        }
 +        if ($param['type'] = 'JSON') {
 +                return new JSONParser($param["filePath"]);
 +        }
 +    }
 +}
 +</file>
 +
 +Ở trên chúng ta có hai class là XMLParser và JSONParser dùng để parse nội dung của tập tin tuỳ thuộc vào tập tin được lưu dưới định dạng là XML hay JSON. Tuy nhiên thay vì tạo parser object trực tiếp từ hai class này mà thông qua một Factory class ParserFactory. 
 +
 +Như ví dụ trên nếu chúng ta thay đổi tên của class XMLParser thì chúng ta chỉ cần thay đổi một dòng code trong method construct của ParserFactory. Nếu như chúng ta không sử dụng Factory thì sẽ phải thay đổi ở tất cả các object được tạo từ class XMLParser.
 +
 +===== Factory Method Pattern =====
  
 Hãy tưởng tượng rằng bạn đang tạo một ứng dụng quản lý hậu cần. Phiên bản đầu tiên của ứng dụng của bạn chỉ có thể xử lý vận chuyển bằng xe tải, vì vậy phần lớn mã của bạn nằm trong lớp Truck. Hãy tưởng tượng rằng bạn đang tạo một ứng dụng quản lý hậu cần. Phiên bản đầu tiên của ứng dụng của bạn chỉ có thể xử lý vận chuyển bằng xe tải, vì vậy phần lớn mã của bạn nằm trong lớp Truck.
Line 8: Line 126:
  
 Kết quả là, bạn sẽ có một mã khá khó chịu, chứa đầy các điều kiện chuyển đổi hành vi của ứng dụng tùy thuộc vào lớp đối tượng phương tiện giao thông. Kết quả là, bạn sẽ có một mã khá khó chịu, chứa đầy các điều kiện chuyển đổi hành vi của ứng dụng tùy thuộc vào lớp đối tượng phương tiện giao thông.
 +
 +{{ :development:software-architecture:design-patterns:factory-method-en.png |}}
 +
 +**Tóm lại:** Method Factory dùng khi có nhiều cách thức khác nhau để đạt được 1 mục tiêu, và để khi thêm một cách thức mới thì chúng ta chỉ cần thêm một Class mới tương ứng không phải sửa quá nhiều code trong function xử lý.
 +
 +**Ví dụ 1:**
 +
 +{{ :development:software-architecture:design-patterns:method-factory-diagram.png |}}
  
 <file php> <file php>
Line 125: Line 251:
 </file> </file>
  
-Trong số những kiểu mẫu thiết kế hay design pattern trong PHP thì Factory là một trong những pattern được sử dụng phổ biến nhất.+**Ví dụ 2:** 
 + 
 +{{ :development:software-architecture:design-patterns:method-factory-social.png |}}
  
 <file php> <file php>
-class XMLParser +<?php 
-    function __construct($filePath) { + 
-        file_get_content($filePath);+namespace RefactoringGuru\FactoryMethod\RealWorld; 
 + 
 +/** 
 + * The Creator declares a factory method that can be used as a substitution for 
 + * the direct constructor calls of products, for instance: 
 + * 
 + * - Before: $p = new FacebookConnector(); 
 + * - After: $p = $this->getSocialNetwork; 
 + * 
 + * This allows changing the type of the product being created by 
 + * SocialNetworkPoster's subclasses. 
 + */ 
 +abstract class SocialNetworkPoster 
 +
 +    /** 
 +     * The actual factory method. Note that it returns the abstract connector. 
 +     * This lets subclasses return any concrete connectors without breaking the 
 +     * superclass' contract. 
 +     */ 
 +    abstract public function getSocialNetwork(): SocialNetworkConnector; 
 + 
 +    /** 
 +     * When the factory method is used inside the Creator's business logic, the 
 +     * subclasses may alter the logic indirectly by returning different types of 
 +     * the connector from the factory method. 
 +     */ 
 +    public function post($content): void 
 +    
 +        // Call the factory method to create a Product object... 
 +        $network = $this->getSocialNetwork(); 
 +        // ...then use it as you will. 
 +        $network->logIn(); 
 +        $network->createPost($content); 
 +        $network->logout();
     }     }
 } }
  
-class JSONParser +/** 
-    function __construct($filePath) { + * This Concrete Creator supports Facebook. Remember that this class also 
-        file_get_content($filePath);+ * inherits the 'post' method from the parent class. Concrete Creators are the 
 + * classes that the Client actually uses. 
 + */ 
 +class FacebookPoster extends SocialNetworkPoster 
 +
 +    private $login, $password; 
 + 
 +    public function __construct(string $login, string $password) 
 +    
 +        $this->login = $login; 
 +        $this->password = $password; 
 +    } 
 + 
 +    public function getSocialNetwork(): SocialNetworkConnector 
 +    { 
 +        return new FacebookConnector($this->login, $this->password);
     }     }
 } }
  
-abstract class ParserFactory +/** 
-    public static function __construct($param) { + * This Concrete Creator supports LinkedIn. 
-         if ($param['type''XML') { + */ 
-                return new XMLParser($param["filePath"])+class LinkedInPoster extends SocialNetworkPoster 
-        } +{ 
-        if ($param['type'] = 'JSON') { +    private $email, $password; 
-                return new JSONParser($param["filePath"]); + 
-        }+    public function __construct(string $email, string $password) 
 +    
 +        $this->email = $email
 +        $this->password = $password; 
 +    
 + 
 +    public function getSocialNetwork(): SocialNetworkConnector 
 +    
 +        return new LinkedInConnector($this->email, $this->password);
     }     }
 } }
 +
 +/**
 + * The Product interface declares behaviors of various types of products.
 + */
 +interface SocialNetworkConnector
 +{
 +    public function logIn(): void;
 +
 +    public function logOut(): void;
 +
 +    public function createPost($content): void;
 +}
 +
 +/**
 + * This Concrete Product implements the Facebook API.
 + */
 +class FacebookConnector implements SocialNetworkConnector
 +{
 +    private $login, $password;
 +
 +    public function __construct(string $login, string $password)
 +    {
 +        $this->login = $login;
 +        $this->password = $password;
 +    }
 +
 +    public function logIn(): void
 +    {
 +        echo "Send HTTP API request to log in user $this->login with " .
 +            "password $this->password\n";
 +    }
 +
 +    public function logOut(): void
 +    {
 +        echo "Send HTTP API request to log out user $this->login\n";
 +    }
 +
 +    public function createPost($content): void
 +    {
 +        echo "Send HTTP API requests to create a post in Facebook timeline.\n";
 +    }
 +}
 +
 +/**
 + * This Concrete Product implements the LinkedIn API.
 + */
 +class LinkedInConnector implements SocialNetworkConnector
 +{
 +    private $email, $password;
 +
 +    public function __construct(string $email, string $password)
 +    {
 +        $this->email = $email;
 +        $this->password = $password;
 +    }
 +
 +    public function logIn(): void
 +    {
 +        echo "Send HTTP API request to log in user $this->email with " .
 +            "password $this->password\n";
 +    }
 +
 +    public function logOut(): void
 +    {
 +        echo "Send HTTP API request to log out user $this->email\n";
 +    }
 +
 +    public function createPost($content): void
 +    {
 +        echo "Send HTTP API requests to create a post in LinkedIn timeline.\n";
 +    }
 +}
 +
 +/**
 + * The client code can work with any subclass of SocialNetworkPoster since it
 + * doesn't depend on concrete classes.
 + */
 +function clientCode(SocialNetworkPoster $creator)
 +{
 +    // ...
 +    $creator->post("Hello world!");
 +    $creator->post("I had a large hamburger this morning!");
 +    // ...
 +}
 +
 +/**
 + * During the initialization phase, the app can decide which social network it
 + * wants to work with, create an object of the proper subclass, and pass it to
 + * the client code.
 + */
 +echo "Testing ConcreteCreator1:\n";
 +clientCode(new FacebookPoster("john_smith", "******"));
 +echo "\n\n";
 +
 +echo "Testing ConcreteCreator2:\n";
 +clientCode(new LinkedInPoster("john_smith@example.com", "******"));
 </file> </file>
  
 +===== Abstract Factory Pattern =====
  
-Ở trên chúng ta có hai class là XMLParser và JSONParser dùng để parse nội dung của tập tin tuỳ thuộc vào tập tin được lưu dưới định dạng là XML hay JSON. Tuy nhiên thay vì tạo parser object trực tiếp từ hai class này mà thông qua một Factory class ParserFactory. +[[development:software-architecture:design-patterns:abstract-factory|Abstract Factory]]
  
-Như ví dụ trên nếu chúng ta thay đổi tên của class XMLParser thì chúng ta chỉ cần thay đổi một dòng code trong method construct của ParserFactory. Nếu như chúng ta không sử dụng Factory thì sẽ phi thay đổi ở tất cả các object được tạtừ class XMLParser.+====== Tham khảo ====== 
 + 
 +  * https://refactoring.guru/design-patterns/factory-method 
 +  * https://refactoring.guru/design-patterns/abstract-factory 
 +  * https://www.youtube.com/watch?v=O6TsDdKtyz0
development/software-architecture/design-patterns/factory.1723642985.txt.gz · Last modified: 2024/08/14 13:43 by tungnt

Donate Powered by PHP Valid HTML5 Valid CSS Driven by DokuWiki