Why do I need a Singleton design template?

I am trying to learn a design pattern, but it is really very difficult to understand the basic idea of โ€‹โ€‹OOD. I created my software using the classic method. On the other hand, I want to find out OOD. why do i need singleton and others? I encoded a simple program: one of them is classic (my style), the other is a singleton pattern. Please teach me why I need a singleton. my method is better and clearer than it :)

my style: (C #)

public partial class Singletonsuz : System.Web.UI.Page { protected void Page_Load(object sender, EventArgs e) { Loadbalancer balancer = new Loadbalancer(); for (int i = 0 ; i < 15 ; i++) { string server = balancer.Server; Response.Write("Dispatch Request to: " + server); } } } class Loadbalancer { private List<string> _servers = new List<string>(); private Random _random = new Random(); public Loadbalancer() { _servers.Add("ServerI"); _servers.Add("ServerII"); _servers.Add("ServerIII"); _servers.Add("ServerIV"); _servers.Add("ServerV"); } public string Server { get { int r = _random.Next(_servers.Count); return _servers[r].ToString(); } } } 

SINGLETON:

 public partial class SingletonDP2 : System.Web.UI.Page { protected void Page_Load(object sender, EventArgs e) { LoadBalancer balancer = LoadBalancer.GetLoadBalancer(); for (int i = 0; i < 15; i++) { string server = balancer.Server; Response.Write("Dispatch Request to: " + server ); } } class LoadBalancer { private static LoadBalancer _instance; private List<string> _servers = new List<string>(); private Random _random = new Random(); private static object syncLock = new object(); protected LoadBalancer() { _servers.Add("ServerI"); _servers.Add("ServerII"); _servers.Add("ServerIII"); _servers.Add("ServerIV"); _servers.Add("ServerV"); } public static LoadBalancer GetLoadBalancer() { if (_instance == null) { lock (syncLock) { if (_instance == null) { _instance = new LoadBalancer(); } } } return _instance; } public string Server { get { int r = _random.Next(_servers.Count); return _servers[r].ToString(); } } } } 
+3
c # oop design-patterns
Jan 27 '09 at 8:02
source share
10 answers

Design patterns are not a design or development methodology. They are a dictionary: they help put names in the repeating patterns that are found in software architectures. In my experience, the development of FROM software templates ends with hairy software with a large number of single-purpose classes, which increases the number of things that a programmer should keep in mind (and software development is complicated enough not to fill your brain with noise).

However, design patterns are very convenient at a later stage. Always start with your specific problem and domain, try to find solutions and identify patterns in the process. Do not start with templates trying to embed your problem in your problem. Knowledge of the most common patterns is mandatory, as it facilitates communication between programmers (whether it is a developer or library users) and promotes best practices.

For example, suppose your problem is with datasets. At some point, you created your data structures and algorithms. Now you (or someone else) need to access your data at a higher level. This is a typical case when Iterator or Visitor templates can be used. This is the way it was done in C ++ STL, where all class classes understand iterators. However, you do not need to think about templates that you can or cannot apply here or there, there is always time to reorganize things after the templates or needs have been identified.

Design models originally come from architecture and buildings, which are very similar to software development. In my experience, the best way to understand DP is the analogy with architecture: software is a building, patterns are how architectural elements are organized: windows, doors, corridors, stairs, lights ... Architects do not think about the elements that they want to use, but think about what effect they want to get. For example, an architect might think: this staircase needs light. To achieve this, he can use windows, skylights, glass blocks, artificial lights, etc. In accordance with architectural restrictions, building code, customer taste, etc. He does not arbitrarily select elements before thinking about a problem that he is trying to solve if he is not trying to achieve an effect or style. Moreover, if another solution becomes available on the market (for example, reflective tunnels of sunlight), then it can integrate it into affordable design patterns for its future projects. OTOH, if he is used to thinking about solutions before thinking about problems, he risks losing alternative solutions, complicating the problem or not solving it at all.

Here you used the Singleton pattern for what seems like a global object that needs dynamic initialization. In this case, Singleton is an acceptable solution. However, sometimes you will need more complex solutions due to external constraints (for example, you need to initialize objects in a specific order), and Singleton is no longer suitable. Or the object will only need static initialization, and a simple global variable will suit your needs.

Using design templates is just as bad as not using them where they are needed. The choice of whether to use a template or not is knowledge and experience in the field of software development and development in general and your area in particular.

+27
Jan 27 '09 at 8:46
source share

You do not need templates. You need solutions to a specific problem. Templates are simply general solutions to known problems and are therefore considered good and working solutions.

The problem with templates is that you can easily find a solution to the problem. those. you start looking for a pattern that fits into the problem, when you should think the other way around: think about the problem, and then try if your solution matches the pattern.

When you have a hammer, everything looks like a nail ...

+10
Jan 27 '09 at 8:17
source share

The Singleton template is widely recognized as not a template. This is more like an example of how to present a template.

You may find that a more general purpose template such as Visitor is more useful.

+5
Jan 27 '09 at 8:08
source share

Singleton is often simply used to justify the existence of a global state.

If you accept a global state and donโ€™t feel the need to wrap it in a pattern, such as singleton, with the possible exception of the following limited circumstances:

You represent this global state from the library.

If you publish it as a simple public static field, it can be extremely difficult to change your decision to rely on a global state (something that could happen).

In these circumstances, presenting the value to the outside world not as a Singleton, but as the default , which is just statically defined, will allow you to change the design (and refuse API users to process it as if it could be only a single instance).

This is really just a Factory, which you are currently implementing is simply

Thus, โ€œhidingโ€ the construct is an important part, not the global nature of the return value.

In cases where class consumers are part of the same assembly process (i.e. if you change the class in any way, the affected code will be directly affected in the next assembly), then you need to make this packaging to allow the change to be controversial question as you can just change it if necessary. This is an application that you do not need. This is a guide.

+5
Jan 27 '09 at 8:29
source share

The Singleton template is an officially recognized way to do something similar to global variables in modern OOP languages. This prevents conflicts of global variable names, etc., since it is isolated from the class, and therefore duplicating class names is easier to avoid (since your compiler will be wrong). It is also easier to create an object with a "lazy instance": you can wait until the object is needed for the first time to create an instance of it as part of a singleton function. This saves some CPU cycles in the long run.

+1
Jan 27 '09 at 8:32
source share

Design patterns are used to structure code in large base codes. Instead of each individual programmer using his own coding style and connecting systems from left to right, you use a design template suitable for the application you are developing. The design pattern basically says how you should structure your code and how different systems should interact with each other.

Using design patterns can speed up development time and can make you think in a way that prevents further problems. If you want to work in the field, training, or at least knowing a lot of design patterns, is paramount. A company with a large software project, created with a specific template, will not kindly look at you if you start writing code, like some kind of cowboy breaking and distorting the chosen idiom. Since this leads to confusion of other developers in the team and, as a rule, complicates the understanding.

0
Jan 27 '09 at 8:12
source share

Singletones are more when you provide code / libraries to others ...

Your first example allows multiple instances and therefore does not follow the singleton pattern.

The second example does not allow multiple instances ... having an open constructor in the first allows several instances of the LoadBalancer. Since in the second example it is protected (closed), and the caller must use "GetLoadBalancer", which checks for the existence of an existing instance, it provides only one copy.

0
Jan 27 '09 at 8:42
source share

Well, you need to know where the cartridge that uses the most important thing is not code specific to the Singleton context you can use if you want to provide a single access point to the methods and properties of the object in your application. Used, for example, in classes that handle access to a table in a database. However, singletones tend to spread across applications, even if you really don't need them.

0
Jan 27 '09 at 8:48
source share

In your example, there is no real benefit if you have only one instance of LoadBalancer. This makes it difficult to understand the potential benefits of Singleton.

The LoadBalancer in your example simply returns random servers.

Imagine a Loadbalancer class that keeps track of which servers it has already returned, so the LoadBalancer can return the server with the least load.

In this situation, it is necessary that all instances of Singletonsuz talk to the same LoadBalancer: if all of them simply created their own (who do not know what other LoadBalancers are doing), then there would be no real balancing and tracking of the returned servers.

If they all need to talk to the same instance, they can call the static GetLoadBalancer, and then this single instance can return the server that was returned the least number of times.

Hope this helps

Jan

0
Jan 27 '09 at 10:13
source share

This is one of the most famous design patterns regarding interview questions.

Imagine a building with G + 4 floors. Each floor has 2 apartments and a total of 8 apartments in the building. On average, 4 members per apartment you should have a minimum of 32 members using the elevator.

Now consider an office building of 8 floors. There are at least 5 offices on each floor, and the number of employees in each of them is never limited.

In the first scenario, we did not need more than one elevator. In the second scenario, one elevator was simply not enough.

Now that you understand the need for a single lift and the need for multiple lifts. This gives us reason to understand Singleton's design scheme.

DESIGNING SINGLETON DESIGN

Like the elevator in the previous example, the Singleton design pattern is also used to create and use ONLY ONE instance of the object.

Why? Because the application does not require more than one object.

If you saw professional offices, you would notice that one printer is used by all employees on the same floor. All students do not keep the printer at home, they prefer to go and pay in a cyber cafe in their colony and use their printer for their instant requirements.

All this, because the given object MUST here. From a software point of view, an object is โ€œexpensiveโ€ when it uses a lot of resources to do its job.

So now we have a need for the Singleton design pattern:

1) when the application will not use this object more than several times throughout the life cycle.

2) when the application needs the object often, but the object itself is very expensive to calculate.

SINGLETON SOFTWARE IMPLEMENTATION

The Singleton design pattern states that: Allow only one instance of the class to be created in the entire application and provide a global access point to it

So, the first part relates to the "limiting" design.

From the first days of the object-oriented implementation in Java, we know that constructors are special functions that are called at run-time and can be made private. When the constructor becomes private, any code outside the class cannot create its own object. Therefore, to implement the Singleton design pattern, we will need a "private constructor", and we will create an object inside the class using this constructor.

The second part of our definition is about providing a global handle to this single object. We will do this using a public method.

0
Oct 11 '16 at 7:45
source share



All Articles