当前位置: 首页 > news >正文

hyperf 创建型(单例、工厂、建造者、原型)

---1. 单例模式 — 全局只有一个 ───────────────────────────────────────────────────────────────────────────────────────────────────────────────────── 大白话: 整个应用只创建一个实例,所有地方用的都是同一个对象。 生活比喻: 公司只有一个CEO,不管谁找CEO,找到的都是同一个人。 什么时候用: 数据库连接池、Redis连接、配置类、日志类。 // Hyperf 里最简单的方式:直接用容器,天然单例 // config/autoload/dependencies.phpreturn[RedisClient::class=>RedisClient::class, // 容器默认就是单例];// 手动实现单例 class Config{private static ?Config$instance=null;private array$data=[];// 构造函数私有,外部不能 new privatefunction__construct(){$this->data=require'config.php';}public staticfunctiongetInstance(): static{if(static::$instance===null){static::$instance=new static();}returnstatic::$instance;}publicfunctionget(string$key): mixed{return$this->data[$key]?? null;}}// 用法:不管调多少次,都是同一个对象$config1=Config::getInstance();$config2=Config::getInstance();var_dump($config1===$config2);// true,同一个 Hyperf 协程注意点: // 协程环境下,单例共享数据会有并发问题 // 用 Context 存请求级别的数据,不要存在单例属性里 class UserContext{public staticfunctionset(User$user): void{Context::set('current_user',$user);// 每个协程独立}public staticfunctionget(): ?User{returnContext::get('current_user');}}---2. 工厂模式 — 专门负责造对象 大白话: 你不用关心对象怎么创建的,告诉工厂你要什么,工厂给你造好。 生活比喻: 你去餐厅点菜,不用管厨房怎么做,说"来份宫保鸡丁",端上来就行。 什么时候用: 创建逻辑复杂、根据条件创建不同对象。 简单工厂 // 根据支付类型,创建不同支付对象 interface PaymentInterface{publicfunctionpay(int$amount): bool;}class AlipayPayment implements PaymentInterface{publicfunctionpay(int$amount): bool{echo"支付宝支付 {$amount} 元";returntrue;}}class WechatPayment implements PaymentInterface{publicfunctionpay(int$amount): bool{echo"微信支付 {$amount} 元";returntrue;}}// 工厂:你告诉我类型,我给你造 class PaymentFactory{public staticfunctioncreate(string$type): PaymentInterface{returnmatch($type){'alipay'=>new AlipayPayment(),'wechat'=>new WechatPayment(), default=>throw new\InvalidArgumentException("不支持的支付方式: {$type}"),};}}// 用法:不用关心怎么 new 的$payment=PaymentFactory::create('alipay');$payment->pay(100);工厂方法(结合 Hyperf 容器) // 更优雅:用 Hyperf 容器做工厂 class PaymentFactory{publicfunction__construct(private ContainerInterface$container){}publicfunctioncreate(string$type): PaymentInterface{$map=['alipay'=>AlipayPayment::class,'wechat'=>WechatPayment::class,];if(!isset($map[$type])){throw new\InvalidArgumentException("不支持: {$type}");}return$this->container->get($map[$type]);}}// Controller 里用 class OrderController{publicfunction__construct(private PaymentFactory$factory){}publicfunctionpay(Request$request): ResponseInterface{$payment=$this->factory->create($request->input('type'));$payment->pay($request->input('amount'));return$this->response->json(['status'=>'ok']);}}---3. 建造者模式 — 一步步组装复杂对象 大白话: 对象太复杂,参数太多,一步步设置,最后 build()出来。 生活比喻: 装修房子,先定墙色、再定地板、再定家具,最后验收交付。不是一次性全说完。 什么时候用: 构造参数超过4个、对象有很多可选配置、需要链式调用。 // 场景:发送消息,有很多可选项 class Message{privatefunction__construct(publicreadonlystring$to, publicreadonlystring$content, publicreadonlystring$type, publicreadonly?string$title, publicreadonlyint$priority, publicreadonly?array$extra,){}public staticfunctionbuilder(string$to, string$content): MessageBuilder{returnnew MessageBuilder($to,$content);}}class MessageBuilder{private string$type='text';private ?string$title=null;private int$priority=0;private ?array$extra=null;publicfunction__construct(private string$to, private string$content,){}publicfunctiontype(string$type): static{$this->type=$type;return$this;// 返回自身,支持链式调用}publicfunctiontitle(string$title): static{$this->title=$title;return$this;}publicfunctionpriority(int$priority): static{$this->priority=$priority;return$this;}publicfunctionextra(array$extra): static{$this->extra=$extra;return$this;}publicfunctionbuild(): Message{returnnew Message(to:$this->to, content:$this->content, type:$this->type, title:$this->title, priority:$this->priority, extra:$this->extra,);}}// 用法:链式调用,清晰直观$message=Message::builder('13800138000','您的订单已发货')->type('sms')->title('订单通知')->priority(1)->extra(['order_id'=>1001])->build();// 实际场景:构建复杂查询条件 class UserQueryBuilder{private array$conditions=[];private ?int$limit=null;private string$orderBy='created_at';publicfunctionactive(): static{$this->conditions['status']=1;return$this;}publicfunctionvip(): static{$this->conditions['is_vip']=1;return$this;}publicfunctionlimit(int$limit): static{$this->limit=$limit;return$this;}publicfunctionorderBy(string$field): static{$this->orderBy=$field;return$this;}publicfunctionbuild(): Builder{$query=User::query();foreach($this->conditions as$field=>$value){$query->where($field,$value);}if($this->limit){$query->limit($this->limit);}return$query->orderBy($this->orderBy);}}// 用法$users=(new UserQueryBuilder())->active()->vip()->limit(10)->orderBy('created_at')->build()->get();---4. 原型模式 — 复制一个现成的 大白话: 创建新对象太麻烦,直接克隆一个现有的,再改改就行。 生活比喻: 合同模板,每次不从头写,复制一份模板改改就发出去。 什么时候用: 对象初始化成本高、需要大量相似对象、配置类对象复用。 // 场景:邮件模板,基础配置一样,只改收件人和内容 class EmailTemplate{publicfunction__construct(public string$from='noreply@example.com', public string$to='', public string$subject='', public string$body='', public array$cc=[], public string$charset='UTF-8', public string$contentType='text/html',){}// 克隆方法 publicfunctionclone(): static{returnclone$this;}// 链式修改 publicfunctionwithTo(string$to): static{$new=$this->clone();$new->to=$to;return$new;}publicfunctionwithSubject(string$subject): static{$new=$this->clone();$new->subject=$subject;return$new;}publicfunctionwithBody(string$body): static{$new=$this->clone();$new->body=$body;return$new;}}// 用法:定义一个基础模板$baseTemplate=new EmailTemplate(from:'order@myshop.com', charset:'UTF-8', contentType:'text/html',);// 克隆出不同邮件,不影响原模板$orderEmail=$baseTemplate->withTo('user@example.com')->withSubject('您的订单已确认')->withBody('<h1>订单确认</h1>');$shipEmail=$baseTemplate->withTo('user@example.com')->withSubject('您的订单已发货')->withBody('<h1>订单发货</h1>');// 注意:clone 是浅拷贝,对象属性要手动深拷贝 class Order{public array$items=[];public Address$address;// 对象属性 publicfunction__clone(){// 深拷贝对象属性,否则克隆体和原对象共享同一个 Address$this->address=clone$this->address;// 数组是值类型,自动深拷贝,不用处理}}--- 四种模式对比 ┌────────┬────────────────────┬──────────────┐ │ 模式 │ 解决什么问题 │ 一句话记忆 │ ├────────┼────────────────────┼──────────────┤ │ 单例 │ 全局只要一个实例 │ 独生子 │ ├────────┼────────────────────┼──────────────┤ │ 工厂 │ 不想关心怎么 new │ 点菜不进厨房 │ ├────────┼────────────────────┼──────────────┤ │ 建造者 │ 参数太多、分步构建 │ 装修房子 │ ├────────┼────────────────────┼──────────────┤ │ 原型 │ 复制现有对象改改用 │ 复印合同模板 │
http://www.jsqmd.com/news/705978/

相关文章:

  • 2026年优质塑料箱模具:周转箱模具/塑料模具加工/塑料箱模具/模具厂家/水果筐模具/模具开模/模具生产厂家/塑料模具/选择指南 - 优质品牌商家
  • 【IEEE文章复现】基于分布式模型预测控制(DMPC)的领航车和多辆跟随车的异构车辆队列在单向通信拓扑下的协同控制研究(Matlab代码实现)
  • 2026年正规自动温控阀TOP5名录:铜截止阀、铜球阀厂家、铜阀门厂家、阀门品牌、黄铜球阀、ppr双活接球阀、ppr热熔阀门选择指南 - 优质品牌商家
  • 2026年现阶段灭菌不锈钢篮生产厂商怎么选?一文读懂关键要素 - 2026年企业推荐榜
  • 2026年4月更新:仿丝棉行业领导者“三兄妹服装辅料”深度解析与选型指南 - 2026年企业推荐榜
  • 2026现阶段大同路缘石厂家深度剖析:趋势、挑战与优选策略 - 2026年企业推荐榜
  • 2026年当前青岛私人向导服务优选指南:聚焦山东佳鑫智慧国际旅行社 - 2026年企业推荐榜
  • 新型电力系统变革前沿:虚拟电厂与储能调峰的数字化深度解析(WORD)
  • 如何免费实现《植物大战僵尸》完美宽屏体验?PvZWidescreen模组终极指南
  • 2026云南货架检测技术指南:房屋安全鉴定/云南地基基础检测公司/云南桥梁检测公司/云南货架检测公司/云南防雷检测公司/选择指南 - 优质品牌商家
  • 4月27日成都地区热镀锌扁钢(鸿翔、百丰、丽泽,型号−20-200mm)现货批发 - 四川盛世钢联营销中心
  • 2026年Q2前瞻:宁波市硅烷处理剂专业服务商深度评估——聚焦宝隆表面处理科技有限公司 - 2026年企业推荐榜
  • 2026年4月盘点:鹤壁不锈钢消防排烟防火阀厂家综合评估与选择标准 - 2026年企业推荐榜
  • 2026年4月临沂面条烘干设备选购指南与专业厂家推荐 - 2026年企业推荐榜
  • 4月27日成都地区热镀锌槽钢(晋南、翅冀、宝得,型号[6.3#-[40#)现货批发 - 四川盛世钢联营销中心
  • 2026年近期察哈尔右翼前旗基建选材:钢筋混凝土水泥涵管诚信工厂深度解析 - 2026年企业推荐榜
  • 2026年4月广东企业灵活用工平台选型指南:数据化解析主流服务商 - 2026年企业推荐榜
  • 【2026年最新600套毕设项目分享】澡堂预订的微信小程序(30178)
  • 基于安卓的机场贵宾接机服务系统毕设源码
  • 2026年4月新消息:东北地区立杆智能喷灌设备优选厂家深度解析 - 2026年企业推荐榜
  • 2026年至今海南艺考培训市场深度解析与机构实力评估** - 2026年企业推荐榜
  • ICOP QEC-M-01 EtherCAT主站系统解析与应用
  • 2026年当前,西安企业如何选择全域营销服务商?陕西摘星人工智能科技有限责任公司实力解析 - 2026年企业推荐榜
  • 2026医学图书出版标杆名录:教辅图书出版/科技类图书出版/经济学理论专著出版/计算机科学学术专著出版/人文社科专著出版/选择指南 - 优质品牌商家
  • 【2026年最新600套毕设项目分享】基于微信小程序的在线选课系统(30179)
  • 【2026年拼多多暑期实习/春招- 4月26日-第二题- 多多的推荐位】(题目+思路+JavaC++Python解析+在线测试)
  • 低场MRI仿真框架:优化非理想磁场下的图像重建
  • 量子机器学习中的领域感知量子电路设计与优化
  • 大模型的探索与实践-课程笔记(十):机器学习发展史
  • 2026年现阶段,如何在长治挑选靠谱的铝镁锰板供应商? - 2026年企业推荐榜