设计模式 一

原文 https://github.com/kamranahmedse/design-patterns-for-humans
作者用简练的语句概括几个设计模式的场景和用法,比看长篇大论心情舒畅多了,简要翻译一下加深记忆 #介绍 设计模式是对某种特定问题的解决之道 #注意 设计模式不是银弹
#设计模式的类型

  • 创造型
  • 结构型
  • 行为型

#创造性设计模式 创造性设计模式专注于如何表达一个object或一组相关的object,通过从某种程度上控制这些object的创造

  • 简单工厂模式
  • 工厂模式
  • 抽象工厂模式
  • 建造者模式
  • 原型模式
  • 单例模式

##简单工厂 为你生成一个实例,掩盖所有生成的细节

###代码实例:

interface Door {
    public function getWidth() : float;
    public function getHeight() : float;
}

class WoodenDoor implements Door {
    protected $width;
    protected $height;

    public function __construct(float $width, float $height) {
        $this->width = $width;
        $this->height = $height;
    }

    public function getWidth() : float {
        return $this->width;
    }

    public function getHeight() : float {
        return $this->height;
    }
}

使用工厂建门

class DoorFactory {
   public static function makeDoor($width, $height) : Door {
       return new WoodenDoor($width, $height);
   }
}

使用

$door = DoorFactory::makeDoor(100, 200);
echo 'Width: ' . $door->getWidth();
echo 'Height: ' . $door->getHeight();

###什么时候使用 当生成一个实例需要一定的逻辑,那把他们放在一个专用的工厂中会比散落在各处写相同的代码好

##工厂模式
让子类定义实例的逻辑,实现抽象父类的方法

###代码实例:

interface Interviewer {
    public function askQuestions();
}

class Developer implements Interviewer {
    public function askQuestions() {
        echo 'Asking about design patterns!';
    }
}

class CommunityExecutive implements Interviewer {
    public function askQuestions() {
        echo 'Asking about community building';
    }
}

使用人事经理为不同的人决定是谁来面试

abstract class HiringManager {

    // Factory method
    abstract public function makeInterviewer() : Interviewer;

    public function takeInterview() {
        $interviewer = $this->makeInterviewer();
        $interviewer->askQuestions();
    }
}

创建各子类继承父类

class DevelopmentManager extends HiringManager {
    public function makeInterviewer() : Interviewer {
        return new Developer();
    }
}

class MarketingManager extends HiringManager {
    public function makeInterviewer() : Interviewer {
        return new CommunityExecutive();
    }
}

使用

$devManager = new DevelopmentManager();
$devManager->takeInterview(); // Output: Asking about design patterns

$marketingManager = new MarketingManager();
$marketingManager->takeInterview(); // Output: Asking about community building.

感觉使用接口也能达到同样的效果,不知为什么要绕道使用继承抽象父类的方式 ###什么时候使用
有共同的方法,但具体需在运行时决定使用哪个子类的逻辑

转载于:https://my.oschina.net/u/3211934/blog/844338

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值