Reputation: 30887
I have a base class (PrintProviderBase
). It holds some states (PrinterUnavailable
, NoPaper
, ...).
Then I inherit from this class : ColorPrintProvider
, BlackAndWhitePrintProvider
...
I was assumed that if the base class has a property like this:
private PrintStateEnum State { get; set; }
Then each child class (different print providers) have it's own state (though nothing is static). It seems one instance of the base
class is shared among them while I meant to have a copy of the base class
in each child class so the common functionality and state can be encapsulate into base class
.
Now if a print provider goes into NoPaper
state, other ones stop printing due to incorrect state. How can I change this behavior ?
Upvotes: 0
Views: 972
Reputation: 4721
In the code you posted, State is a private to PrintProviderBase and would not be visible to the derived types like ColorPrintProvider and so on.
Make State a public property and use Composition not inheritance. Keep a member of PrintProvider (change the name from PrintProviderBase) in ColorPrintProvider, BlackAndWhitePrintProvider and so on.
Sample code:
public class PrinterState
{
public Boolean IsPaperTrayEmpty { get; set; }
public Int32 CartridgeLevel { get; set; }
}
public class ColorPrintProvider
{
public PrinterState CurrentState { get; private set; }
private void UpdateCurrentState()
{
// update the current state
// based on / after some events like RequestForPrint, PrintCompleted...
}
}
Upvotes: 1
Reputation: 386
Each instance of ColorPrintProvider and BlackAndWhitePrintProvider will have their own (and distinct) instance of the State value, although none of them will be able to access it unless you make it public or protected (or provide other properties or methods which expose it). In general the value would only be shared across instances if it were static.
Upvotes: 2