dongtaogou6226 2012-02-19 00:54
浏览 72
已采纳

PHP - 如何跨多个子类共享设置并实例化这些共享设置一次?

Let's say I have 3 PHP classes: ShedBuilder, HouseBuilder and TableBuilder and the following code:

$worker_1 = new ShedBuilder(); // I only know how to build a shed
$worker_2 = new HouseBuilder(); // I only know how to build a house
$worker_3 = new TableBuilder(); // I only know how to build a table

$worker_1->build();
$worker_2->build();
$worker_3->build();

I want worker_1, worker_2, and worker_3 classes to each share the same toolset for the job, for example, I want all 3 workers to use the tools available, in this case a hammer, screwdriver, nails, etc. But worker_1 will build a shed, worker_2 will build a house, worker_3 builds a table.

What's the best way to set the toolset once and then have each of the 3 workers know how to access the tools they need for the job?

I thought about having Shed/Table/House builder each extend from a parent class, Builder, but that means that when I instantiate each I have to give them each the toolset:

$toolset = new Toolset();
$toolset->addTool('hammer');
$toolset->addTool('screwdriver');
$toolset->addTool('nails');

$worker_1 = new ShedBuilder($toolset);
$worker_2 = new HouseBuilder($toolset);
$worker_3 = new TableBuilder($toolset);

I'd rather instantiate the tools once and then have all 3 workers/classes know about the toolset and build each of their items, respectively.

What's the best way to implement what I'm trying to do in PHP?

  • 写回答

2条回答 默认 最新

  • douchongbang6011 2012-02-19 00:58
    关注

    What you have already, instantiating a Toolset and providing $toolset to each of the worker classes in their constructors, is called Dependency Injection, and it is actually the preferred way of handling this task most of the time.

    It is possible to accomplish it by creating a singleton Toolset object, however that is unnecessary when dependency injection handles it in a tidy and easily testable way.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥50 易语言把MYSQL数据库中的数据添加至组合框
  • ¥20 求数据集和代码#有偿答复
  • ¥15 关于下拉菜单选项关联的问题
  • ¥20 java-OJ-健康体检
  • ¥15 rs485的上拉下拉,不会对a-b<-200mv有影响吗,就是接受时,对判断逻辑0有影响吗
  • ¥15 使用phpstudy在云服务器上搭建个人网站
  • ¥15 应该如何判断含间隙的曲柄摇杆机构,轴与轴承是否发生了碰撞?
  • ¥15 vue3+express部署到nginx
  • ¥20 搭建pt1000三线制高精度测温电路
  • ¥15 使用Jdk8自带的算法,和Jdk11自带的加密结果会一样吗,不一样的话有什么解决方案,Jdk不能升级的情况