简体   繁体   中英

asp.net mvc4 EF5 Singleton?

I have a project going on and I'd like to have one unique instance of a class.

I have a 'JobOffer' class, which has a property of type 'OfferStatus' (which is abstract and implements a state pattern). I have 'StateAvailable' and 'StateUnavailable' (or 'open' and 'closed' if you wish). The 'JobOffer' objects have to be stored in the db.

I'd like to have just one 'StateAvailable' and one 'StateUnavailable', so when I create a new JobOffer I reference to 'StateAvailable' or 'StateUnavailable', and then I could list all the jobOffers which are Open (available) and all that are Closed (unavailable).

I know that I could do this by adding the states in the db in the seed method, and never instantiate a new state. But I was wondering if it is possible to do a singleton or something to avoid that somebody (I mean controller, model or anything) can create new instances of that class.

public class JobOffer {
public int JobOfferId {get;set;}
public OfferState State {get;set;
public virtual ICollection<Person> People {get;set;}

//And some methods here, which depends on the state
//ie, this.State.myMethod();

My first thought was to use a boolean. Then you said you have to be able to expand to have more states, so I thought of an enum. Then you said you have this requirement to use a class, so... here's a little something I use when I want an enum with more smarts. You could call it a sort of "enumerating class", I suppose. So, your OfferState class looks like this:

public sealed class OfferState
{
    public bool CanChangeState { get; set; }
    //whatever properties you need

    public static OfferState Available = new OfferState(true);
    public static OfferState Unavailable = new OfferState(true);
    public static OfferState Closed = new OfferState(false);
    //whatever states you need

    public OfferState(bool canChange)
    {
        CanChangeState = canChange;
    }
}

This acts kind of like an enum, but it has properties like a class. So in your logic, you can check state:

if (jobOffer.State == OfferState.Available)
{
    //stuff
}

You can also get properties off it, so you can use it to get information about the state:

jobOffer.ExpiryDate = jobOffer.CreationDate.Add(OfferState.Available.MaxDuration);

And of course, the static nature of the various states will ensure that there's only ever one instance of each.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM