dimanche 2 avril 2017

Design system for a given Article class with states

Having the following problem. Article goes through several stages before being published by several different Roles.

Writer -> writes
Approver -> approves
Admin -> Publishes

Design a program that allow for maximum extensibility: This is what I have. Can someone please let me know if this is the right approach? is there a better one?

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();
    }
}

internal class Program
{
    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.Publish();
    }
}

Aucun commentaire:

Enregistrer un commentaire