Abstract class singleton C# - c#

public sealed class HomePage : Page
{
public override void GoTo()
{
throw new System.NotImplementedException();
}
public override void IsAt() => Assert.IsTrue(Browsers.Title.Equals("home"));
}
I have bunch of page object classes like HomePage which I want to turn into a singleton.
I was looking at Jon Skeet's site on implementing the Singleton pattern.
An example of how to implement the Singleton pattern as per the site mentioned above:
public sealed class Singleton {
private static readonly Singleton instance = new Singleton();
static Singleton() {}
private Singleton() {}
public static Singleton Instance {
get {
return instance;
}
}
}
I want to implement this for all my page objects. All my page objects inherit from an abstract base class Page.
public abstract class Page
{
private static readonly Page instance = new Page();
public abstract void IsAt();
public abstract void GoTo();
}
I'm trying to implement the Singleton pattern I mentioned earlier on my Page base class. But the problem is my Page class is abstract and I can't do the following:
private static readonly Page instance = new Page(); // Since Page is abstract I can't do this.
How can I implement the singleton pattern without having to implement it for each child class individualy?

Your question is specifically about being able to implement the singleton pattern solely using the base class, without making any code changes to the derived classes.
It's possible to do something like this:
public abstract class Page
{
// Your normal Page base class things
}
public abstract class Page<T> : Page where T : Page<T>, new()
{
// Or whatever singleton pattern you want to implement
public static readonly T Instance = new T();
}
public class HomePage : Page<HomePage>
{
}
This lets you write:
var homePage = HomePage.Instance;
This works because Page<T> has its own set of static data which is separate for each T - so Page<HomePage> has separate static data to Page<LogInPage>.
You will however need to modify each of your pages to derive from Page<PageSubclass>, rather than from Page.
That said, I would take the simpler route of adding code like:
public static readonly HomePage Instance = new HomePage();
to each of your Page subclasses. This is significantly less "magic", doesn't rely on reflection to instantiate the pages, and will only take you a few minutes to add to even 70 page objects. After all, you'll have to modify them all to derive from Page<T> to use this pattern anyway.

You can kind of do this, but just because you can do something, it does not mean it is a good idea. Think if it really makes the code easier to understand or not. Sometimes the amount of abstraction makes it just not worth it
public abstract class Page<T> where T: new()
{
public static readonly T instance = new T();
public abstract void GoTo();
}
public class Home : Page<Home>
{
public override void GoTo()
{
Console.WriteLine("goto home");
}
}
public class Login : Page<Login>
{
public override void GoTo()
{
Console.WriteLine("goto Login");
}
}
Then:
Home.instance.GoTo();
Login.instance.GoTo();
The thing is it is not a nice pattern. You might be better doing something like this so you avoid singletons:
pages["Home"].Goto();

Related

C#: Protected Variables inside of a Generic Class can be accessed by a different subclass of that Generic Class. Can I prevent this?

Say I have a generic class Foo, that has a variable that is protected
public class Foo<T>
{
protected bool knowsFu;
}
I also have 2 sub-classes: Bar and Pipe
public class Bar : Foo<Bar> {}
public class Pipe : Foo<Pipe> {}
It is actually possible for me to access the knowsFu in Pipe FROM Bar, e.g.:
public class Bar : Foo<Bar>
{
void UpdateFuInOtherClass(Pipe p)
{
p.knowsFu = false;
}
}
Is this intended behaviour? (If so, what would be the usecase?)
Is there a way for me to prevent other Foo-Subclasses from modifying/reaching the protected variable inside of my current subclass?
More specifically: I'm using a generic class to implement the Singleton-Pattern:
https://en.wikipedia.org/wiki/Singleton_pattern
However, I'm currently able to access any singleton's protected instance-variable, as long as I am inside of another Singleton. Is there a way to prevent this?
EDIT: It might be relevant to note that the protected variable (knowsFu) is actually STATIC as well.
EDIT2: Ok, maybe the example was abit too generic.. here's how I'm actually currently implementing it:
why use Singleton? A:The platform I'm working on is Unity3D, in which the pattern is used frequently
I have a generically typed abstract class SingletonBehaviour
public abstract class SingletonBehaviour<T> where T : MonoBehaviour
{
public static T Instance { get { return instance; } }
protected static T instance { get; private set; } }
// Loading is done through Unitys Awake-Method
}
One of the Singleton-Objects that I'm using is the APIManager
public class APIManager : SingletonBehaviour<APIManager>
{
// Methods like SendHTTPPost(), HTTPGet(), etc.
}
However, since most of my projects need some better API-implementation than that, what I'm currently doing is:
public class ProjectAAPIManager : APIManager
{
// Overriding Instance so my return value is not APIManager but instead ProjectAAPIManager
public static new ProjectAAPIMamager Instance { get { return (ProjectAAPIManager)instance; } }
}
This ^ is the reason my (inner) instance-variable is protected, and not private.
However, because of this, any other SingletonBehaviour in my project can now access the (inner) instance-variable on my ProjectAAPIManager
public class GameController : SingletonBehaviour<GameController>
{
private void AMethod()
{
// Accessing inner variable instead of public one
ProjectAAPIManager.instance.DoSomething();
}
}
As it's only the getter, this currently does not really matter. But what if I'd need access to the setter in my subclass as well?
Also: would it be worth it to generically type my APIManager as well?
Your question is nothing short of bewildering. How can you make a protected member not be accesible from a derived class? Well, a good start is not making it protected.
protected is by definition exactly what you don't want, so don't use it! Use private instead.
If what you are asking is how to make it a readonly member when accessed from derived types, you have two options:
Declare it as readonly in the base class if possible.
Use a protected property instead with a private setter.
Many novice coders seems to think protected members aren't part of the public surface of the type but they really are, as long as the class can be extended. As such, the rules of public members apply: never expose public fields unless they are readonly or constants, use properties instead.
You should not have classes that implement your generic singleton class.
Otherwise, by default, your protected fields will be accessible by the subclasses (it's what "protected" keyword does)
Instead, you should do something like this:
class Program
{
static void Main(string[] args)
{
var barInstance = Foo<Bar>.GetInstance();
}
}
public class Foo<T> where T : new()
{
protected bool knowsFu;
private static T _instance;
public static T GetInstance()
{
if (_instance == null)
_instance = new T();
return _instance;
}
}
public class Bar
{
public Bar()
{
}
}
Edit 1:
To use a singleton, you should not make another class implement the singleton behavior (This is not how the singleton pattern works).
To use the same classes as your second example, you should do something like this.
public class SingletonBehaviour<T> where T : new()
{
public static T Instance
{
get
{
if(instance == null)
instance = new T()
return instance;
}
}
private static T instance { get; set; }
}
public class APIManager // This class should not inherit from the SingletonBehavior class
{
// Methods like SendHTTPPost(), HTTPGet(), etc.
}
public class ProjectAAPIManager : APIManager
{
public ProjectAAPIManager GetInstance() => SingletonBehavior<ProjectAAPIManager>.Instance();
}

Instantiate another class in sealed class

What is the recommended way to instantiate another class inside a sealed class:
public sealed class AvayaService
{
private static Lazy<AvayaService> lazy =
new Lazy<AvayaService>(() => new AvayaService());
public static AvayaService AvayaServiceInstance
{
get
{
if (!lazy.IsValueCreated)
lazy = new Lazy<AvayaService>(() => new AvayaService());
return lazy.Value;
}
}
private AvayaService()
{
}
public static Response GetResponse(Request request)
{
var _repository = new Repository(); // what is the best way to get the instance here
}
}
public class Repository : IRepository
{
...
}
I am trying to learn sealed class and lazy instantiation however I am pondering over what should be the recommended way to instantiate another class in a sealed class?
There's no "recommendations" in this area. If you've read recommendations, read again, most probably it was just an exercise. It gives you an idea, but using this idea in a real project is up to you. Sometimes those exercises demonstrate an opposite approaches. Sometimes the repository owner will dictate the style which is against of any rules you've read before, and it's totally fine.
Here's another instantiation exercise which I think is helpful to try: to never instantiate anything except value objects. Delegate instantiation to a container. Avoid singleton pattern, but register your service as a singleton in your container. In this way your code will look like:
public sealed class AvayaService
{
private readonly IRepository _repository;
public AvayaService(IRepository repository)
{
if(repository == null)
throw new ArgumentNullException();
_repository = repository;
}
public static Response GetResponse(Request request)
{
// use _repository
}
}

How can I implement a Singleton class that can be derived from in WPF?

Some time ago I learned of the Singleton implementation that only permits a single instance of a class object by hiding the class initializer and using a private static reference of the object within itself, and a public GETTER that references that private reference -
public class Foo : IDisposable{
private static Foo _Instance;
public static Foo Instance{ get{ return Foo._Instance ?? new Foo(); }
private Foo(){ Foo._Instance = this; }
public void Dispose(){ Foo._Instance = null; }
}
I love this quite a lot - it is especially nice for windows that I want accessible application wide.
One thing that I would really like is to be able to implement a generic sort of Singleton Window class upon which a real window could be built and then accessed like this - Is this possible? My thinking was something like -
public class SingletonWindow : Window {
private static SingletonWindow _Instance;
public static SingletonWindow Instance{ get{ return SingletonWindow._Instance ?? new SingletonWindow(); } }
private SingletonWindow(){ SingletonWindow._Instance = this; }
private sealed override void OnClosed(EventArgs E){ SingletonWindow._Instance = null; }
}
But... something inside me that I can't quite voice tells me that this will absolutely positively fail miserably. Can someone tell me why this would fail (if, indeed it will fail), if it is possible to achieve what I am attempting to achieve here, and how I might go about doing so if it is possible?
Personally, I'm not a fan of singletons.
That said, if you want a generic class, make it a generic class. You will have to have a static constructor on your derived class that will provide a route to the private constructor to your generic class, but that's about it.
public abstract class Singleton<T> where T : Window, Singleton<T>
{
protected static Func<T> create;
private static T instance;
public static T Instance { get { return instance ?? (instance = create()); } }
private sealed override void OnClosed(EventArgs e)
{
instance = null;
}
}
public class MyWindow : Singleton<MyWindow>
{
static MyWindow()
{
create = () => new MyWindow();
}
private MyWindow() { }
}
Then you can access the instance on your derived class as if it was a normal singleton.
var myWindow = MyWindow.Instance;

Can I move the static access to the base class?

I have a base and derived class like so:
public abstract class MyBase
{
protected string _data;
protected string GetData_Internal() {return _data;}
protected abstract void SetData(string data);
}
public class MyDerived : MyBase
{
protected override void SetData(string data) {_data = "my data";}
public static string GetData()
{
var instance = new MyDerived();
return instance.GetData_Internal();
}
}
The desired usage of this class is like this:
string data1 = MyDerived.GetData();
string data2 = MyDerived2.GetData(); // another class dervied from MyBase
I can't make the classes static, because static classes and derived classes don't play well together. So I made the function GetData() static, and this allows me to use the class like I want to.
I am going to have multiple classes that all identical to MyDerived, except for the data values set in SetData().
I would like to move GetData() out of the derived class and into the base class so that I'm not duplicating that code in every single derived class.
I can't figure out how to do that, because a static method in the base class has no idea what type of object to new up.
So, is there any way to do what I'm trying to do, keeping a static interaction with the class, while avoiding code duplication to make it happen?
If you are working with static data, maybe what you need are singleton objects that can be instantiated only once. They have the advantage of supporting inheritance and interface implementation, as well as being accessible statically. Also, unlike static classes, they can be passed as arguments to methods and stored in fields, properties and variables.
You can use properties instead of getter and setter methods. This simplifies your base class:
public abstract class MyBase
{
public string Data { get; set; }
}
You can implement the singleton pattern like this:
public class MyDerived : MyBase
{
#region Singleton Pattern
public static readonly MyDerived Instance = new MyDerived();
private MyDerived()
{
}
#endregion
}
Create a public static readonly field that returns the only instance of the class and make the constructor private in order to forbid creating instances outside of the class itself. The constructor can also initialize the value of Data if required.
You can use the singletons like this:
MyDerived.Instance.Data = "my data";
string data = MyDerived.Instance.Data;
MyDerived2.Instance.Data = "my data 2";
...
See also: Implementing Singleton in C# for various ways of implementing the singleton pattern.
First, I am not completely sure what it is you are trying to accomplish. So, I am making no comment on if any of this is a good idea. You can get behavior that acts somewhat like overridden methods on base classes with statics. Instead, you overwrite the base then call into it. I do something similar to this for fetching instances or collections of instances from the class:
public class Dog
{
public static Dog GetById(int dogId)
{
//Return dog
}
}
public class Lab : Dog
{
public new static Lab GetById(int dogId)
{
//Return same dog, as a lab
}
}
A quick and terrible, but hopefully useful, version might start like the following. I might be able to make it into something practical if I understand your intentions a bit better.
public abstract class MyBase
{
public static string GetData()
{
return "BASE STUFF";
}
}
public class MyDerivedA : MyBase
{
protected const string MySpecialData = "AAAAAA";
public new static string GetData()
{
return MyBase.GetData() + MySpecialData;
}
}
public class MyDerivedB : MyBase
{
protected const string MySpecialData = "BBBBBBB";
public new static string GetData()
{
return MyBase.GetData() + MySpecialData;
}
}

How can I factor out the code duplication here?

So, I'd like to hear what you all think about this.
I have a project where three different inheritance paths need to all implement another base class. This would be multiple inheritance and isn't allowed in C#. I am curious how I can implement this without code duplication.
EDIT: I don't own the three classes. The three classes are from 3rd party code. So I cannot make them all extend my base class.
Right now I am using three different classes, each one extending a different base class. Then I have the same code in each of the three abstract classes.
I could use a single interface, but I would still need to duplicate the code.
I could make some kind of static class that implements the code and then reference that in each of the 3 abstract classes. It would eliminate the duplication, but, I am not sure how I feel about this. I could implement Extensions methods on the interface, but then the interface itself would be empty and the extension methods (containing the duplicate code) would be in a totally different file, which seems not quite right. Plus I can't implement properties in extension methods...
How can I factor out the code duplication here?
EDIT, inheritance tree:
class Class1 : 3rdPartyBaseClass1 { }
class Class2 : 3rdPartyBaseClass2 { }
class Class3 : 3rdPartyBaseClass3 { }
I have code I want to be in each of the above Classes, but I cannot add it to the 3rdPartyClasses.
Create an interface that Class1, Class2, and Class3 can implement. Then put your code in extension methods so it will apply to all.
interface IMyInterface {
void Foo(); //these are the methods that these
//classes actually have in common
void Bar();
}
public class Class1 : 3rdPartyBaseClass1, IMyInterface {
// whatever
}
public static class IMyInterfaceExtensions {
public static void CommonMethod(this IMyInterface obj) {
obj.Foo();
obj.Bar();
}
}
public static class Program {
public static void Main() {
var instance = new Class1();
instance.CommonMethod();
}
}
OK, you can do something similar to my previous suggestion, and also similar to recursive's suggestion. For the functionality you require in all three of your derived classes, you can create a single Interface along with a single class (call it "Implementer" for kicks) that implements that Interface (and that has the actual code you want executed with each call).
In each of your derived classes, then, you implement the Interface and create a private instance of Implementer. In each of the interface methods, you just pass the call along to the private instance of Implementer. Because Implementer and your derived classes all implement your Interface, any changes you make to the Interface will require you to modify Implementer and the derived classes accordingly.
And all your code is in one place, except for all the lines passings the calls on to the private instance of Implementer (obviously multiple inheritance would be better than this, but you go to war with the army you have, not the army you wish you had).
Update: what about just adding a public instance of your class to each of the derived classes?
public class DerivedClass1 : ThirdPartyClass1
{
public MyClass myClass = new MyClass();
}
Or if you care who Demeter is and you get paid by LOC:
public class DerivedClass1 : ThirdPartyClass1
{
private MyClass _myClass = new MyClass();
public MyClass myClass
{
get
{
return _myClass;
}
}
}
Then you'd just call the MyClass methods like this:
DerivedClass1 dc1 = new DerivedClass1();
dc1.myClass.DoSomething();
This way, we could all go to sleep.
Similar to MusiGenesis's suggestion, if you need the functionality of the 3rd party classes but do not have to descend from them, you could use composition as follows:
class ThirdPartyBaseClass1
{
public void DoOne() {}
}
class ThirdPartyBaseClass2
{
public void DoTwo() { }
}
class ThirdPartyBaseClass3
{
public void DoThree() { }
}
abstract class Base
{
public void DoAll() { }
}
class Class1 : Base
{
public void DoOne() { _doer.DoOne(); }
private readonly ThirdPartyBaseClass1 _doer = new ThirdPartyBaseClass1();
}
class Class2 : Base
{
public void DoTwo() { _doer.DoTwo(); }
private readonly ThirdPartyBaseClass2 _doer = new ThirdPartyBaseClass2();
}
class Class3 : Base
{
public void DoThree() { _doer.DoThree(); }
private readonly ThirdPartyBaseClass3 _doer = new ThirdPartyBaseClass3();
}
This also gives you the freedom to define whatever interfaces you want and implement them on your classes.
Sounds like you need to insert the new abstract class into the inheritance tree at whatever point those three paths come together, but there really isn't enough information to tell. If you could post some of your inheritance tree, that would help a lot.
I think you may want to use composition instead of inheritance. Exactly how to do this depends on what the third party classes look like, and what your own code looks like. Some more specific code relating to your problem would be helpful, but for example, suppose you want to have three different third party GUI widgets that all need to be customized with your own initializer code.
Case 1: Suppose your third party widgets look like:
public interface IThirdPartyWidget {
public void doWidgetStuff();
}
public class ThirdPartyWidget1: ThirdyPartyWidget implements IThirdPartyWidget {
...
}
public class ThirdPartyWidget2: ThirdPartyWidget implements IThirdPartyWidget {
...
}
You can do:
public class MyWidget implements IThirdPartyWidget {
private IThirdPartyWidget delegateWidget;
public MyWidget(IThirdPartyWidget delegateWidget) {
this.delegateWidget = delegateWidget;
}
public void doWidgetStuff() {
delegateWidget.doWidgetStuff();
}
}
Case 2: Suppose you absolutely need to extend those widgets, and you have to refactor your own code:
public class MyWidget1: ThirdPartyWidget1 {
public void myMethod() {
runMyCode();
}
private void runMyCode() {
//something complicated happens
}
}
public class MyWidget2: ThirdPartyWidget2 {
public void myMethod() {
runMyCode();
}
private void runMyCode() {
//something complicated happens
}
}
This can become:
public class MyCodeRunner {
public void runMyCode() {
//...
}
}
public class MyWidget1: ThirdPartyWidget1 {
private MyCodeRunner myCode = new MyCodeRunner();
public void myMethod() {
myCode .runMyCode();
}
}
public class MyWidget2: ThirdPartyWidget2 {
private MyCodeRunner myCode = new MyCodeRunner();
public void myMethod() {
myCode .runMyCode();
}
}
Hope this makes sense!

Categories