I read a lot about singleton is tightly couple but I do not understand how it is tightly coupled. Can you give small example for that?
Asked
Active
Viewed 1,523 times
1 Answers
3
From Scott Densmore,
Singletons tightly couple you to the exact type of the singleton object, removing the opportunity to use polymorphism to substitute an alternative.
Link: https://blogs.msdn.microsoft.com/scottdensmore/2004/05/25/why-singletons-are-evil/
For example if you had an abstract base class:
public abstract class Connection{
...
public abstract void getConnection();
}
And an implementation
public class OracleConnection extends Connection{
...
@Override
public void getConnection(){
InitializeOracle();
}
}
And another
public class PostgresConnection extends Connection{
...
@Override
public void getConnection(){
InitializePostgres();
}
}
With a singleton pattern, you're stuck with whatever original global connection object you had. Sucks if you want to use one or the other or both at run time. You can't.
By definition of the singleton, the above would just be in one concrete class with no extensions and you would only have one connection object. Not very flexible. Like this:
final class Connection {}
public class Connection{
...
public void getConnection(){
InitializeConnection(); // you're totally stuck with this connection
}
}

Alexander Kleinhans
- 5,950
- 10
- 55
- 111