mardi 8 octobre 2019

Abstract class singleton 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 classes individualy?

Aucun commentaire:

Enregistrer un commentaire