策略模式问题-PHP
我有一个 Person 类,我想使用策略模式来添加存储行为。像这样
interface Storage{
public function store();
}
class LocalStorage implements Storage(){
public function store(){
..
// save in a file
..
}
}
class Person{
private $behaviourStorage;
private $name;
private $age;
public function __construct(Storage $objStorage,$name,$age) {
$this->behaviourStorage = $objStorage;
}
public function Store(){
$this->behaviourStorage->store();
}
}
$objPerson = new Person(new LocalStorage(),'John',32);
我的问题是,如何使用存储行为来保存对象 person 的信息?如何将对象传递到 LocalStorage 以便它知道要保存什么?
也许这毕竟不是正确的设计模式,但意图很明确:为 person 对象实现不同的存储行为。
I have a class Person and I would like using the Strategy pattern to add a storage behavior. Something like this
interface Storage{
public function store();
}
class LocalStorage implements Storage(){
public function store(){
..
// save in a file
..
}
}
class Person{
private $behaviourStorage;
private $name;
private $age;
public function __construct(Storage $objStorage,$name,$age) {
$this->behaviourStorage = $objStorage;
}
public function Store(){
$this->behaviourStorage->store();
}
}
$objPerson = new Person(new LocalStorage(),'John',32);
My question is, how can I use the storage behavior to save the information of the object person ? How do I pass the object to the LocalStorage so it knows what to save ?
Maybe this is not the right design pattern after all but the intent is clear : implement different storage behaviours for the person object.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
修改
Person::Store()
以便它调用$this->behaviourStorage->store($this)
,然后检查传递的对象中的字段到该方法,或者让它使用要存储的字段值调用$this->behaviourStorage->store()
。Either modify
Person::Store()
so that it calls$this->behaviourStorage->store($this)
, and then examine the fields in the object passed to that method, or have it call$this->behaviourStorage->store()
with the field values to store.