Can we inherit singleton class?
It depends on implementation. Singletons usually have private constructor and possibly marked sealed, if it is so then you can't. If it is at least protected you can. If you just inherit from singleton class, result will not be singleton so you should follow the pattern and make it also singleton.
Yes you can. Keep base class constructor protected (and not private).
Then derived class can be instantiated but base class cannot be (even inside function definitions of derived class). I've tried this and it works well.
If you cannot inherit from a singleton class, you might as well have implemented that class using only static methods, properties, fields and events.
Being able to access an object of a derived class through a static method (or property) of the base class is one of the key concepts of the Singleton pattern. To quote from Design Patterns: Elements of Reusable Object-Oriented Software (Gamma et. al.):
Applicability
Use the Singleton pattern when
there must be exactly one instance of a class, and it must be accessible to clients from a well-known access point.
when the sole instance should be extensible by subclassing, and clients should be able to use an extended instance without modifying their code.
(emphasis by me)
Here's a possible way to handle a derived Singleton:
public abstract class Singleton<T> where T : Singleton<T>, new() {
private static readonly T s_instance = new T();
protected Singleton() {
if (s_instance != null) {
string s = string.Format(
"An instance of {0} already exists at {0}.instance. " +
"That's what \"Singleton\" means. You can't create another.",
typeof(T));
throw new System.Exception(s);
}
}
public static T instance { get { return s_instance; } }
}
public class MyClass : Singleton<MyClass> {
}
Sure. Why not? The inheriting class will be a specialization of the base Singleton class.
Instances of each of these classes (the base class and the specialized one) will be completely separate. In other words, their Instance members will point to separate objects.
Only the singleton class itself can create an instance... so I supposse the answer is not. I think you can do it, but then it will not be a singleton any more :D
Related
Is there a way of forcing a (child) class to have constructors with particular signatures or particular static methods in C# or Java?
You can't obviously use interfaces for this, and I know that it will have a limited usage. One instance in which I do find it useful is when you want to enforce some design guideline, for example:
Exceptions
They should all have the four canonical constructors, but there is no way to enforce it. You have to rely on a tool like FxCop (C# case) to catch these.
Operators
There is no contract that specifies that two classes can be summed (with operator+ in C#)
Is there any design pattern to work around this limitation?
What construct could be added to the language to overcome this limitation in future versions of C# or Java?
Using generics you can force a type argument to have a parameterless constructor - but that's about the limit of it.
Other than in generics, it would be tricky to actually use these restrictions even if they existed, but it could sometimes be useful for type parameters/arguments. Allowing static members in interfaces (or possibly static interfaces) could likewise help with the "generic numeric operator" issue.
I wrote about this a little while ago when facing a similar problem.
Not enforced at compile-time, but I have spent a lot of time looking at similar issues; a generic-enabled maths library, and an efficient (non-default) ctor API are both avaiable in MiscUtil. However, these are only checked at first-usage at runtime. In reality this isn't a big problem - your unit tests should find any missing operator / ctor very quickly. But it works, and very quickly...
You could use the Factory pattern.
interface Fruit{}
interface FruitFactory<F extends Fruit>{
F newFruit(String color,double weight);
Cocktail mixFruits(F f1,F f2);
}
You could then create classes for any type of Fruit
class Apple implements Fruit{}
class AppleFactory implements FruitFactory<Apple>{
public Apple newFruit(String color, double weight){
// create an instance
}
public Cocktail mixFruits(Apple f1,Apple f2){
// implementation
}
}
This does not enforce that you can't create instance in another way than by using the Factory but at least you can specify which methods you would request from a Factory.
Force Constructors
You can't. The closest that you can come is make the default constructor private and then provide a constructor that has parameters. But it still has loopholes.
class Base
{
private Base() { }
public Base(int x) {}
}
class Derived : Base
{
//public Derived() { } won't compile because Base() is private
public Derived(int x) :base(x) {}
public Derived() : base (0) {} // still works because you are giving a value to base
}
The problem in the language is that static methods are really second class citizens (A constructor is also a kind of static method, because you don't need an instance to start with).
Static methods are just global methods with a namespace, they don't really "belong" to the class they are defined in (OK, they have access to private (static) methods in the class, but that's about it).
The problem on the compiler level is that without a class instance you don't have a virtual function table, which means you cannot use all the inheritance and polymorphism stuff.
I think one could make it work by adding a global/static virtual table for each class but if it hasn't been done yet, there's probably a good reason for it.
Here is I would solve it if I were a language designer.
Allow interfaces to include static methods, operators and constructors.
interface IFoo
{
IFoo(int gottaHaveThis);
static Bar();
}
interface ISummable
{
operator+(ISummable a, ISummable b);
}
Don't allow the corresponding new IFoo(someInt) or IFoo.Bar()
Allow constructors to be inherited (just like static methods).
class Foo: IFoo
{
Foo(int gottaHaveThis) {};
static Bar() {};
}
class SonOfFoo: Foo
{
// SonOfFoo(int gottaHaveThis): base(gottaHaveThis); is implicitly defined
}
class DaughterOfFoo: Foo
{
DaughhterOfFoo (int gottaHaveThis) {};
}
Allow the programmer to cast to interfaces and check, if necessary, at run time if the cast is semantically valid even if the class does not specify explicitly.
ISummable PassedFirstGrade = (ISummable) 10;
Unfortunately you can't in C#. Here is a punch at it though:
class Program
{
static void Main(string[] args)
{
Console.WriteLine(Foo.Instance.GetHelloWorld());
Console.ReadLine();
}
}
public class Foo : FooStaticContract<FooFactory>
{
public Foo() // Non-static ctor.
{
}
internal Foo(bool st) // Overloaded, parameter not used.
{
}
public override string GetHelloWorld()
{
return "Hello World";
}
}
public class FooFactory : IStaticContractFactory<Foo>
{
#region StaticContractFactory<Foo> Members
public Foo CreateInstance()
{
return new Foo(true); // Call static ctor.
}
#endregion
}
public interface IStaticContractFactory<T>
{
T CreateInstance();
}
public abstract class StaticContract<T, Factory>
where Factory : IStaticContractFactory<T>, new()
where T : class
{
private static Factory _factory = new Factory();
private static T _instance;
/// <summary>
/// Gets an instance of this class.
/// </summary>
public static T Instance
{
get
{
// Scary.
if (Interlocked.CompareExchange(ref _instance, null, null) == null)
{
T instance = _factory.CreateInstance();
Interlocked.CompareExchange(ref _instance, instance, null);
}
return _instance;
}
}
}
public abstract class FooStaticContract<Factory>
: StaticContract<Foo, Factory>
where Factory : IStaticContractFactory<Foo>, new()
{
public abstract string GetHelloWorld();
}
Well, I know from the wording of your question you are looking for compile-time enforcement. Unless someone else has a brilliant suggestion/hack that will allow you to do this the way you are implying the compiler should, I would suggest that you could write a custom MSbuild task that did this. An AOP framework like PostSharp might help you accomplish this at comiple-time by piggy backing on it's build task model.
But what is wrong with code analysis or run-time enforcement? Maybe it's just preference and I respect that, but I personally have no issues with having CA/FXCop check these things... and if you really want to force downstream implementers of your classes to have constructor signatures, you can always add rules run-time checking in the base class constructor using reflection.
Richard
I'm unsure as to what you are trying to achieve, can you please elaborate? The only reason for forcing a specific constructor or static method accross different classes is to try and execute them dynamically at run time, is this correct?
A constructor is intended to be specific to a particular class, as it is intended to initialise the specific needs of the class. As I understand it, the reason you would want to enforce something in a class hierarchy or interface, is that it is an activity/operation relevant to the process being performed, but may vary in different circumstances. I believe this is the intended benefit of polymorphism, which you can't achieve using static methods.
It would also require knowing the specific type of the class you wanted to call the static method for, which would break all of the polymorphic hiding of differences in behaviour that the interface or abstract class is trying to achieve.
If the behaviour being represented by the constructor is intended to be part of the contract between the client of these classes then I would add it explicitly to the interface.
If a hierarchy of classes have similar initialisation requirements then I would use an abstract base class, however it should be up to the inheriting classes how they find the parameter for that constructor, which may include exposing a similar or identical constructor.
If this is intended to allow you to create different instances at runtime, then I would recommend using a static method on an abstract base class which knows the different needs of all of the concrete classes (you could use dependency injection for this).
I know that title is little bit to long, so here is my problem .
I've got this class for example:
public class Connection
{
public static Connection Create()
{
return new Connection();
}
}
I need to ensure that new instances of Connection can be created only by other classes , calling the Create method.The solution must allow classes to inherit from Connection.
Some of the answers I've found is to make class abstract or static but as I remember, you can't make instance of abstract or static class nor inherit from static.
The other two offered answers is to make private or protected constructor of Connection class.Well, if constructor is set on private , we can't call him from derived class , but if it is protected, we can .
So , my idea is to make constructor protected.Am i right ?Because I found that someone posted making Connection class static is right answer, and that doesn't make any sense .
Both static and abstract are out for the reasons that you outlined in your question. The way to let other classes inherit from yours, while prohibiting direct instantiation is to make the constructor protected. Keep in mind, however, that an inheriting class can choose to allow its own constructor to be public, thus circumventing your protection.
In general, though, a class should be designed either for inheritance or for instantiation, but not for both purposes at the same time. A better design would be as follows:
public abstract class Connection {
protected Connection();
public static Connection Create() {
return new DefaultConnection();
}
}
internal sealed class DefaultConnection : Connection {
public DefaultConnection() {
...
}
}
Classes from outside can inherit Connection, but they cannot instantiate it because it's abstract. Your code, on the other hand, can create instances of DefaultConnection, which is hidden from everybody else because it is internal.
If you create it as a child class in main class, set the constructor to take a parameter which is generated internally in main class and verified using a private method in main class.
This way no external class can't instantiate the child class without throwing an exception.
What are the ways to create a non-instantiable class? One way is by declaring it as an abstract class. Is it possible to do it by making the class constructor as private? Is a sealed class, non-instantiable? And, are there any other ways to do it in C#?
Marking a class as abstract or static (they are mutually exclusive) are the only two ways. Marking all constructors as private does not make the class uninstantiateable since the class can still construct itself, and others might be able to do it via reflection.
Only static looks like complete solution here because abstract class still can be instantiated when class instance that inherits from it is instantiated. Consider the scenario :
abstract class A { }
class B : A { }
somewhere in code :
B instance = new B(); // this creates instance of class A as well
P.S.
At first i though that abstract sealed might be solution for this problem as well but it doesn't make much sense to use such a construction so it doesn't even compile :
Error 1 'A': an abstract class cannot be sealed or static D:\Projects\TEST\Testapp\Program.cs 15 27 ITT.Domain
As answered by others abstract and static classes cannot be instantiated however a class with private constructor can be by using a public member function. This is how the singleton pattern works
internal classes are only visible inside of your assembly and therefore cannot be instantiated outside of this assembly.
But as far as i know, you could still create an instance via reflection.
you can disable reflection via ReflectionPermission Class
As mentioned above you could declare it as abstract or add an abstract method.
If you just want to declare a contract, you could use an interface, but that's not a class at all.
sealed means you cannot inherit this class
singleton classes can only be created once per application
singleton
see sealed (C# reference)
I currently have a class in which I only have static members and constants, however I'd like to replace it with a singleton wrapped in an interface.
But how can I do this, bearing in mind that every singleton implementation I've seen has a static Instance method, thus breaking interface rules?
A solution to consider (rather than hand-rolling your own) would be to leverage an IoC container e.g. Unity.
IoC containers commonly support registering an instance against an interface. This provides your singleton behaviour as clients resolving against the interface will receive the single instance.
//Register instance at some starting point in your application
container.RegisterInstance<IActiveSessionService>(new ActiveSessionService());
//This single instance can then be resolved by clients directly, but usually it
//will be automatically resolved as a dependency when you resolve other types.
IActiveSessionService session = container.Resolve<IActiveSessionService>();
You will also get the added advantage that you can vary the implementation of the singleton easily as it is registered against an interface. This can be useful for production, but perhaps more so for testing. True singletons can be quite painful in test environments.
You can't do this with interfaces since they only specify instance methods but you can put this in a base class.
A singleton base class:
public abstract class Singleton<ClassType> where ClassType : new()
{
static Singleton()
{
}
private static readonly ClassType instance = new ClassType();
public static ClassType Instance
{
get
{
return instance;
}
}
}
A child singleton:
class Example : Singleton<Example>
{
public int ExampleProperty { get; set; }
}
A caller:
public void LameExampleMethod()
{
Example.Instance.ExampleProperty++;
}
You can make all the other members of your singleton implement corresponding members in an interface. However, you are correct that the Instance property cannot be part of the interface since it is (and must remain) static.
Interfaces can not have instances in C#, I think you only need to:
Implement the singleton pattern (yes, you'll need a static attribute or method to get the instance, but everything else does not require to be static)
On the other hand, your singleton can implement an interface if you want, just remember that other classes can also implement that same interface
Neither is instantiable. What are the differences, and in what situations might you use one or the other?
static indicates the class can only have static members and you cannot create an instance of it. This is used for stateless functionality (for example a type that just defines extension methods, or utility methods). You can also declare a member static on a non-static class. This allows you to attach functionality to a type without having to instantiate it.
Here's more detail on using static members and classes.
abstracts define the basic structure and functionality shared by all derivative types, but cannot be used by themselves. Think of them as, I suppose, a blue print and a contract. This is a core concept for OOP.
Here's more detail on using abstracts.
Here is a short summary:
A static class can only contain static members (it is just a container for methods that do not logically belong to an instance of any standard class)
An abstract class can contain all usual kinds of members (static, abstract and also instance)
The key difference is that you can inherit from an abstract class, but you cannot inherit from a static class. Technically speaking, the .NET runtime doesn't have any notion of static classes, so the C# compiler compiles them as classes that are both abstract and sealed (meaning that you cannot inherit from them).
So, static classes are abstract classes that are also sealed (although this is not the usual way to look at the problem if you are C# programmer) and contain only static members (which is enforced by the C# compiler).
An abstract class is intended to be used as a base of a class inheritance hierarchy. A static class cannot be the base of a class inheritance hierarchy.
A static class is intended for singleton state or stateless functionality. An abstract class is not suitable for singleton functionality, because, even though it may contain static methods and fields as a static class does, it cannot forbid inheritance, so the singleton use may be defeated by subclasses. Or, at the very least, it would be confusing to other programmers, because its definition would communicate an intent that is different from its actual intended use.
The superficial similarity between abstract and static classes is only in the fact that neither may be instantiated. Beyond that, they are completely different animals with completely different use cases.
The CLR has no notion of static classes, it is specific to C#. The compiler implements it by slick use of CLR attributes for a class: it declares it abstract and sealed. That prevents any language from instantiating such a class. This is what it looks like when you run Ildasm:
.class public abstract auto ansi sealed beforefieldinit ConsoleApplication1.Test
extends [mscorlib]System.Object
{
}
Making it sealed is very much the point of a static class, it is used as a container for static methods and fields. Which makes them act like global variables and functions like you have in languages like C or Pascal.
An abstract class is very much the opposite, it is designed to be derived from. A abstract class that has all of its member abstract acts like an interface. C# has a keyword for that, making static class and interface the exact opposites.
Abstract classes get instantiated indirectly via derived classes. They provide common behaviour and instance state, but signal that more is required and must be provided by derived concrete classes. For example, Transform might be an abstract class: it declares a common Apply(Shape) method, but no implementation of that method. Concrete derived classes like Rotation or Translation will implement that method, and those classes can be instantiated.
Static classes cannot be instantiated, and any state is at the class level rather than the instance level. They are typically used to define utility methods where there is no state associated with the methods. Transform couldn't be a static class, because the concrete derived classes need per-instance state (e.g. Rotation needs a per-instance Angle, because different Rotation transforms could be by different angles).
Abstract classes are intended to be used as base classes; they cannot have direct instances. Instead, you have to derive subclasses, which provide the what was (usually intentionally) left out in the abstract base class.
Example: consider you have a complex application, where users may log-in to. Various authentication mechanisms should be usable, say, LDAP, NTLM, you name it. One way to model a "user" or "principal" in such a context would be to collect, what is common across all those mechanisms, into an abstract base class, and leave "gaps" (abstract methods) where the actual implementations come into play:
abstract class Authenticator {
protected Dictionary<string,User> userCache;
...
public User LoadUser(string name) {
User user;
if( userCache.TryGet(name, out user) ) return user;
else {
user = LoadFromStore(name);
userCache.Add(name, user);
return user;
}
}
protected abstract User LoadFromStore(string name);
}
Here, caching of users is a common concern, modelled in the base case, whereas the actual retreival is left for a subclass to provide.
Static class are a different matter alltogether. They are essentially a place to keep your utility functions:
static class StrUtil {
public static string TrimWhitespace(string str) {
...
}
}
Think of them as some kind of special namespace, which can only contain static members. Basically, a place to put functions.
Abstract Class (Base class):
Enables other classes to inherit from this class (one class acquires the properties (methods and fields) of another) , but forbids to instantiate i.e we cannot have objects of this class.
http://csharp.net-tutorials.com/classes/abstract-classes
Static Class:
This class cannot be instantiated. Also this class cannot be inherited. To access methods of this class, you can directly use classname.method.
https://social.technet.microsoft.com/wiki/contents/articles/21028.difference-between-static-class-sealed-class-and-abstract-class-in-c.aspx
Abstract class main purpose is to define one or more abstract method(s).
Any class extending Abstract class will implement the abstract method or else its also need to be declared as "Abstract".
But, its also possible to declare a class as "Abstract" without implementing any abstract method(s) in it. See the sample below.
public abstract class AbstractTest {
public void abcd(){}
public static void main(String[] args) {
System.out.print("hi...");
}
}
Only inner class can be declared as "Static", see the code below.
Upper/encapsulating class can't be declared as "Static".
It can be accessed by using Upper/encapsulating class variable.Static-inner-classname i.e same as any static method invocation using class name.
public class StaticTest {
public static void main(String ag[]){
System.out.println("hello...1");
StaticTest.StaticTest2.meth2();
}
public static class StaticTest2 {
public static void meth2(){
System.out.print("hello...2");
}
}
}
Main difference between the two is extensibility.
CLR marks all 'static' classes as 'abstract & sealed' behind the scene (i.e., they cannot be inherited hence cannot be extended) and .NET Framework CLR loads them automatically when containing program or namespace is loaded. This gives performance gain on runtime.
Philosophy behind 'abstract' classes is capitalizing all common features of all extended classes in one place.
Hope it helps.