我想創建一個投票系統,在多個領域對象可以進行表決:這是一個很好的工廠候選人嗎?
- 日曆事件
- 評論
- 用戶
所以我想我會創建一個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