出现以下问题。文章经过几个阶段后才被几个不同的角色发表。
Writer -> writes
Approver -> approves
Admin -> Publishes
设计一个允许最大可扩展性的程序: 这就是我所拥有的。如果这是正确的方法,有人可以告诉我吗?有更好的吗?
public interface IRole
{
IRole Write();
IRole Approve();
IRole Publish();
}
internal class Writer : IRole
{
public IRole Write()
{
return new Approver(); // next needs approval
}
public IRole Approve()
{
return this;
}
public IRole Publish()
{
return this;
}
}
internal class Approver : IRole
{
public IRole Write()
{
return new Writer();
}
public IRole Approve()
{
// publish
return new Admin();
}
public IRole Publish()
{
return this;
}
}
internal class Admin : IRole
{
public IRole Write()
{
return new Writer();
}
public IRole Approve()
{
return new Approver();
}
public IRole Publish()
{
return this;
}
}
internal class Article
{
public Article()
{
role = new Writer();
}
private IRole role { get; set; }
public void Write()
{
role = role.Write();
}
public void Approve()
{
role = role.Approve();
}
public void Publish()
{
role = role.Publish();
}
}
private static void Main(string[] args)
{
var article = new Article();
article.Approve(); // can't do - write first
article.Write();
article.Publish(); // can't do
article.Approve(); // can
article.Write(); // can go back
article.Approve(); // can
article.Publish();
}
答案 0 :(得分:1)
您正在寻找的是" 责任链"。它是一种设计模式,允许操作一个接一个地链接。您的用例将完全符合此模式。 https://www.codeproject.com/Articles/594974/Chain-of-Responsibility-Pattern