我想创建一个投票系统,在多个领域对象可以进行表决:这是一个很好的工厂候选人吗?
- 日历事件
- 评论
- 用户
所以我想我会创建一个Voteable
接口,用于以下项目:
interface Voteable
{
public function vote(User $user, $value);
}
我认为这vote
方法将代理信息库方法,是这样的:
class VotingRepository
{
public function castVote(Voteable $item, User $user, $value)
{
// save the these values, along with the value
$itemId = $item->getId();
$userId = $user->getId();
}
}
目前,该库将是一个数据库。这个数据库将对每种类型的投票链接表:
- eventVote
- commentVote
- userVote
所以,这基本上意味着,每个域对象需要另一个表来投的票。这会成为工厂的一个很好的候选人吗? A VotingRepositoryFactory
在这种情况下?换句话说是这样的:
class VotingRepositoryFactory
{
createVotingRepository($type)
{
switch($type)
{
case 'event':
// create a voting repository with EventVote table
return new VotingRepository(new EventVoteTable());
case 'comment':
// create a voting repository with CommentVote table
return new VotingRepository(new CommentVoteTable());
case 'user':
// create a voting repository with UserVote table
return new VotingRepository(new UserVoteTable());
}
}
}
然后,域对象中尝试所有这些,从(在这种情况下,例如评论),我会是这个样子:
class Comment implements Voteable
{
public function construct()
{
$this->_repository = VotingRepositoryFactory::createVotingRepository('comment');
}
public function vote(User $user, $value)
{
$this->_repository->castVote($this, $user, $value);
}
}
这是否合理?
只要记住不要太过分的设计模式。设计模式在有效且审慎地使用时会创建优雅且易于维护的代码。然而,你也想避免建造10英尺脚手架的陷阱,只是为了把你的钟挂在墙上。这就是说,我喜欢在太多的脚手架上犯错。 ;-) – 2010-02-25 21:26:56
@Jeff:我听到你在说什么。该网站将是一个相当雄心勃勃的项目(至少对我而言)。所以我希望它可以从git go尽可能保持。 – 2010-02-25 21:39:24