Abstract factory pattern (PHP)

The PHP sample code of the abstract factory pattern is easy to understand the design pattern quickly.

  1. Structure diagram
    Before
    Insert picture description here
    optimization: After optimization:Insert picture description here

  2. Mask factory

interface IMask {
    
    
    function showMask();
}

class LowEndMask implements IMask {
    
    
    public function showMask(){
    
    
        echo "我的低端口罩\n";
    }
}

class HighEndMask implements IMask {
    
    
    public function showMask(){
    
    
        echo "我的高端口罩\n";
    }
}
  1. Protective clothing factory
interface IProtectiveSuit {
    
    
    function showSuit();
}

class LowEndProtectiveSuit implements IProtectiveSuit {
    
    
    public function showSuit(){
    
    
        echo "我是低端防护服\n";
    }
}


class HighEndProtectiveSuit implements IProtectiveSuit {
    
    
    public function showSuit(){
    
    
        echo "我是高端防护服\n";
    }
}
  1. High-level factories and low-level factories
interface IFactory {
    
    
    //创建口罩
    function createMask();
    //创建防护服
    function createSuit();
}

class LowEndFactory implements IFactory {
    
    
    public function createMask() {
    
    
        $mask =  new LowEndMask();
        // .....
        //  LowEndMask的100行初始化代码
        return $mask;
    }

    public function createSuit() {
    
    
        $suit =  new LowEndProtectiveSuit();
        // .....
        //  LowEndProtectiveSuit的100行初始化代码
        return $suit;
    }
}

class HighEndFactory implements IFactory {
    
    
    public function createMask() {
    
    
        $mask =  new HighEndMask();
        // .....
        // HighEndMask的100行初始化代码
        return $mask;
    }

    public function createSuit() {
    
    
        $suit =  new HighEndProtectiveSuit();
        // .....
        //  HighEndProtectiveSuit的100行初始化代码
        return $suit;
    }
}
  1. Test interface
class Test {
    
    

    public function main() {
    
    
        $factoryA = new LowEndFactory();
        $factoryB = new HighEndFactory();
        //创建低端口罩
        $maskA = $factoryA ->createMask();
        //创建高端口罩
        $maskB = $factoryB ->createMask();
        //创建低端防护服
        $suitA = $factoryA ->createSuit();
        //创建高端防护服
        $suitB = $factoryA ->createSuit();

        $maskA->showMask();
        $maskB->showMask();
        $suitA->showSuit();
        $suitB->showSuit();
    }
}

$tst = new Test();
$tst ->main();

Result:
Insert picture description here
Reference: https://mp.weixin.qq.com/s/K_E9pI5rnkjHU0eizg9lqg

Guess you like

Origin blog.csdn.net/qq_36453564/article/details/108576796