php与Python常见的设计模式实现

问题:

为什么要使用设计模式

是为了解决重复性问题的通用解决方案

为什么要学习设计模式

更轻松的对源代码进行阅读与审计

设计模式分类

创建者模式

工厂模式

php
<?php
interface Transport{
    public function weight();
}


class bus implements Transport{
    public function weight()
    {
        // TODO: Implement go() method.
        return "bus 比较大.";
    }
}

class car implements Transport
{
    public function weight()
    {
        // TODO: Implement weight() method.
        return "car 比较小";
    }
}

class bike implements Transport{
    public function weight()
    {
        // TODO: Implement weight() method.
        return "Bike 超级小";
    }
}


class Run{
    public static function trun($transport)
    {
        switch ($transport) {
            case 'bus':
                return new bus();
                break;

            case "car":
                return new car();
                break;

            case 'bike':
                return new bike();
                break;
        }
    }
}

$tansport = Run::trun('car');
echo $tansport->weight();
?>
Python
from abc import abstractmethod,ABCMeta

class Interface(metaclass=ABCMeta): # netaclass 定义抽象类
    @abstractmethod # abstractamethod 定义抽象方法
    def weigth(self):
        pass

class bus(Interface):
    def weigth(self):
        return "bus 是超大的"

class car(Interface):
    def weigth(self):
        return "car 是一般大的"

class bike(Interface):
    def weigth(self):
        return "Bike 是很小的"

class Run:
    @staticmethod ## 定义静态方法
    def trun(tansport):
        if(tansport == 'bus'):
            return bus()
        elif(tansport == 'car'):
            return car()
        elif(tansport == 'bike'):
            return bike()


tansport = Run.trun('bus')
print(tansport.weigth())

抽象工厂

php
<?php
interface eat{
    public function run();
}

interface sport{
    public function go();
}


class catSport implements sport{
    public function go()
    {
        // TODO: Implement go() method.
        return "cat 开始行走了";
    }
}

class dogSport implements sport{
    public function go()
    {
        // TODO: Implement go() method.
        return 'dog 开始行走了';
    }
}

class dogEat implements eat{
    public function run()
    {
        // TODO: Implement run() method.
        return 'dog 开始吃饭了';
    }
}

class catEat implements eat{
    public function run()
    {
        // TODO: Implement run() method.
        return "cat 开始吃饭了";
    }
}


abstract class AbcGc{
    abstract protected function getSport($pet);
    abstract protected function getEat($pet);
}


class sportAbcGc extends AbcGc{
    public function getEat($pet)
    {
        // TODO: Implement getEat() method.
    }
    public function getSport($pet)
    {
        // TODO: Implement getSport() method.

        switch($pet){
            case 'dog':
                return new dogSport();
            case 'cat':
                return new catSport();
        }
    }
}

class eatAbcGc extends AbcGc{
    public function getEat($pet)
    {
        // TODO: Implement getEat() method.
        switch($pet){
            case 'dog':
                return new dogEat();
            case 'cat':
                return new catEat();
        }
    }
    public function getSport($pet)
    {
        // TODO: Implement getSport() method.
    }
}

class Factory{
    public function getFactory($pet){
        switch($pet){
            case 'eat':
                return new eatAbcGc();
            case 'sport':
                return new sportAbcGc();
        }
    }
}

$pro = new Factory();
$eat = $pro->getFactory('eat');
$cat_eat = $eat -> getEat('cat');
echo "{$cat_eat->run()}";
?>
Python
from abc import ABCMeta,abstractmethod

class eat(metaclass=ABCMeta):
    @abstractmethod
    def run(self):
        pass

class sport(metaclass=ABCMeta):
    @abstractmethod
    def go(self):
        pass
class catEat(eat):
    def run(self):
        return "猫猫开始吃饭了"

class catSport(sport):
    def go(self):
        return "猫猫开始运动了"

class dogEat(eat):
    def run(self):
        return '狗狗开始吃饭了'

class dogSport(sport):
    def go(self):
        return '狗狗开始运动了'

class abcGc(metaclass=ABCMeta):
    @abstractmethod
    def getEat(self,pet):
        pass
    def getSport(self,pet):
        pass

class eatAbc(abcGc):
    def getEat(self,pet):
        if(pet == 'dog'):
            return dogEat()
        elif(pet == 'cat'):
            return catEat()
    def getSport(self,pet):
        pass

class sportAbc(abcGc):
    def getSport(self,pet):
        if(pet == 'dog'):
            return dogSport()
        elif(pet == 'cat'):
            return catSport()

class Factory:
    @staticmethod
    def run(factory):
        if(factory == 'eat'):
            return eatAbc()
        elif(factory == 'sport'):
            return sportAbc()


eat = Factory.run('eat')
eat_cat = eat.getEat('cat')
print(eat_cat.run())

单例模式

php
<?php
class dl{
    static private $instance;
    private $config;
    private function __construct($config)
    {
        $this->config = $config;
    }
    static function instance($config){
        if(!(self::$instance instanceof self)){
            return new self($config);
        }
        return self::$instance;
    }
}
?>
python
class dl:
    def __init__(self):
        pass
    @classmethod
    def _instance(cls,*args,**kwargs):
        if not hasattr(dl,"instance"):
            dl._instance = dl(*args,**kwargs)
        return dl._instance

结构型

组合模式

PHP
<?php
abstract class CompanyBase{
    abstract function create();
}
class createleaf extends CompanyBase{
    private $name;
    private $size;
    private $color;
    private $leaf = array();
    public function create()
    {
        // TODO: Implement create() method.
        $this->leaf[$this->name] = array(
            'size'=>$this->size,
            'color'=>$this->color
        );
        return $this->leaf;
    }
}
?>
Python
class createLeaf(object):
    def __init__(self,name,size,color):
        self.name = name
        self.size = size
        self.color = color
        self.leaf = {}

    def create(self):
        self.leaf[self.name] = {
            'size':self.size,
            'color':self.color
        }
        return self.leaf


a = createLeaf('含羞草','5cm','绿色')
print(a.create())

装饰器模式

php
<?php
class echotext{
    protected $dex = array();
    public function Index(){
        $this->beforeEcho();
        echo "Hello zsq";
        $this->afterEcho();
    }

    public function addDe(zsq $de){
        $this->dex[] = $de;
    }

    protected function beforeEcho(){
        foreach($this->dex as $de){
            $de->before();
        }
    }
    protected function afterEcho(){
        $tmp = array_reverse($this->dex);

        foreach($tmp as $de){
            $de->after();
        }
    }

}

interface zsq{
    public function before();
    public function after();
}

class color implements zsq{
    protected $color;
    function __construct($color)
    {
        $this->color = $color;
    }

    public function before()
    {
        // TODO: Implement before() method.
        echo "<div style='color:{$this->color};'>";
    }
    public function after()
    {
        // TODO: Implement after() method.
        echo "</div>";
    }
}
$cl = new echotext();
$cl->addDe(new color('red'));
$cl->Index();
?>
Python
def func(de):
    def war():
        print("what?")
        de()
        print("yes")
    return war

@func
def way():
    print("way")

way()

外观模式

php
<?php

class subA{
    public function one()
    {
        // TODO: Implement one() method.
        echo "子系统方法一";
    }
}

class subB{
    public function tow()
    {
        // TODO: Implement one() method.
        echo "子系统方法一";
    }
}

class subC{
    public function three()
    {
        // TODO: Implement one() method.
        echo "子系统方法一";
    }
}

class system_sub{
    function __construct()
    {
        $this->one = new subA();
        $this->tow = new subB();
        $this->three = new subC();
    }
    function methodA(){
        echo "这是方案1";
        $this->one->one();
        $this->tow->tow();
    }
    function methodB(){
        echo "this is method tow";
        $this->tow->tow();
        $this->three->three();
    }
}

?>
Python
class subA:
    def one(self):
        print("this is one from subA")
        
class subB:
    def tow(self):
        print("this is tow from subB")

class subC:
    def three(self):
        print("this is three from subC")
        

class system:
    def __init__(self):
        self.one = subA()
        self.tow = subB()
        self.three = subC()
        
    def methodA(self):
        print("this is method A")
        self.one.one()
        self.tow.tow()
    
    def methodB(self):
        print("this is method B")
        self.tow.tow()
        self.three.three()

本文链接:

http://f4ckweb.top/index.php/archives/30/
1 + 8 =
1 评论
    NkChrome 73Windows 10
    4月27日 回复

    不弄群了吗大佬