开发者

C# Access Modifier depending on state

开发者 https://www.devze.com 2022-12-16 23:20 出处:网络
Assuming an Order(Aggregate class) with Credit Card class as a property. Depending on the state of开发者_JS百科 Order I want to change the access modifier of the Credit Card class properties. For exam

Assuming an Order(Aggregate class) with Credit Card class as a property. Depending on the state of开发者_JS百科 Order I want to change the access modifier of the Credit Card class properties. For example: if Order state = Order.NewOrder, then allow Credit Card properties to be modifiable, however if Order state = Order.CompletedOrder, I do not want to allow the properties in Credit Card to be settable.

I want to be able to check at compile time vs run-time.

The only solution I thought of was to create 2 classes inheriting from the same parent class; one that allows properties to be settable the other not, but it gets hairy very quickly if there is a state that require some properties to be settable and others not.

Any ideas are greatly appreciated.


I'd represent the credit card object with a couple different interfaces. One would have setters and another getters. The CreditCard property on the Order class would only be the getter interface.

class CreditCardBase : ICreditCard 
{
    string Name { get; }
}

interface IWritableCreditCard : ICreditCard
{
    string Name { get; set; }
}

class WritableCreditCard : CreditCardBase, IWritableCreditCard {}

class Order
{
    private ICreditCard _card = new WritableCreditCard(); //initially...
    public ICreditCard Card { get {return _card; } }

    void OnComplete(...) { _card = new CreditCardBase(copy from _card); }
}

At run-time cast "Card" the property to the setter interface to modify the card's properties. If the order state is now in the read-only state, then the object implementing the CreditCard would have been swapped out with an implementation that only implements the getters.

I don't see how you could differentiate at compile time, but at least the normal actions would be the safe "getter only" calls, and the modify code would be a) ugly and easy to detect and b) would return null or throw if executed at the wrong time.


Another way to solve this problem is in 'Design Patterns' pg.208-209 as a Protection Proxy.

The Proxy pattern "provides a surrogate or placeholder for another object to control access to it." You put a protection proxy version of the object in place of the actual object and access logic in the protection proxy returns read-only data, but checks when write is attempted.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号