
Design Patterns – Test
test your skills
test your skills
adapter rabbitmq

The Adapter pattern translates one interface (an object’s properties and methods) to another. Adapters allows programming components to work together that otherwise wouldn’t because of mismatched interfaces. The Adapter pattern is also referred to as the Wrapper Pattern.
One scenario where Adapters are commonly used is when new components need to be integrated and work together with existing components in the application.
Another scenario is refactoring in which parts of the program are rewritten with an improved interface, but the old code still expects the original interface.
Adapter dofactory – link
Class code: Adapter – 3D shape example
Class code: Adapter employee example
Class code: Adapter for flight system

RabbitMQ is a message-queueing software also known as a message broker or queue manager. Simply said; it is software where queues are defined, to which applications connect in order to transfer a message or messages.

A message can include any kind of information. It could, for example, have information about a process or task that should start on another application (which could even be on another server), or it could be just a simple text message. The queue-manager software stores the messages until a receiving application connects and takes a message off the queue. The receiving application then processes the message.
A message broker acts as a middleman for various services (e.g. a web application, as in this example). They can be used to reduce loads and delivery times of web application servers by delegating tasks that would normally take up a lot of time or resources to a third party that has no other job.

Possible message deliver mechanism:
RabbitMQ Enable Web Management Plugin
http://localhost:15672/
username: guest
password: guest 
Download the RabbitMQ prerequisite – link
Download the RabbitMQ – link
Installation tutorial – link
RabbitMQ demo code
Class code: Rabbit Listener
Class code: Rabbit Producer
More topics covered:
Links:
command fluent flyweight weak reference

The Command pattern encapsulates actions as objects. Command objects allow for loosely coupled systems by separating the objects that issue a request from the objects that actually process the request. These requests are called events and the code that processes the requests are called event handlers.
Suppose you are building an application that supports the Cut, Copy, and Paste clipboard actions. These actions can be triggered in different ways throughout the app: by a menu system, a context menu (e.g. by right clicking on a textbox), or by a keyboard shortcut.
Command dofactory – link
Command dotnettutorials – link
Class code: Command – azure example
Class code: Command – javascript example
A fluent interface is normally implemented by using method chaining to implement method cascading, concretely by having each method return this (self). Stated more abstractly, a fluent interface relays the instruction context of a subsequent call in method chaining, where generally the context is
Note that a “fluent interface” means more than just method cascading via chaining…
Class code: fluent – LINQ
Class code: fluent Customer
The Flyweight pattern conserves memory by sharing large numbers of fine-grained objects efficiently. Shared flyweight objects are immutable, that is, they cannot be changed as they represent the characteristics that are shared with other objects.
Essentially Flyweight is an ‘object normalization technique’ in which common properties are factored out into shared flyweight objects. (Note: the idea is similar to data model normalization, a process in which the modeler attempts to minimize redundancy). An example of the Flyweight Pattern could be a is a list of immutable strings that are shared across the application.
Other examples include characters and line-styles in a word processor, or ‘digit receivers’ in a public switched telephone network application. You will find flyweights mostly in utility type applications such as word processors, graphics programs, and network apps; they are less often used in data-driven business type applications.
Flyweight dofactory – link
Flyweight dotnettutorials – link
Class code: Flyweight – big numbers
Class code: Flyweight – java GUI example
Objects that are referenced must be kept in memory until they are unreachable. use the WeakReference type, which leaves objects accessible in memory until they are collected by the Garbage Collector (GC).
If you have cache layer implemented with C# it’s much better too put your data in cache as weak references, it could help to improve your cache layer performance. Think that approach also could be applied to session implementation. Because session is long living object most of the time, it could be some case when you have no memory for new user. In that case it will be much better to delete some else user session object then throwing OutOfMemoryException.
Also, if you have a large object in your application (some big lookup table, etc), that should be used quite seldom and recreating of such an object isn’t a very expensive procedure. Then better have it like a week reference to have a way to free your memory when you really need that.
More topics covered:
Links:
mediator builder observer

The Builder pattern allows a client to construct a complex object by specifying the type and content only. Construction details are hidden from the client entirely.
The most common motivation for using Builder is to simplify client code that creates complex objects. The client can still direct the steps taken by the Builder without knowing how the actual work is accomplished. Builders frequently encapsulate construction of Composite objects because the procedures involved are often repetitive and complex. Usually it is the last step that returns the newly created object which makes it easy for a Builder to participate in fluent interfaces in which multiple method calls, separated by dot operators, are chained together (note: fluent interfaces are implementation of the Chaining Pattern as presented in the Modern patterns section).
Builder dofactory – link
Builder dotnettutorials – link
Class code: builder – hamburger!
The Observer pattern offers a subscription model in which objects subscribe to an event and get notified when the event occurs. This pattern is the cornerstone of event driven programming, The Observer pattern facilitates good object-oriented design and promotes loose coupling.
When building web apps you end up writing many event handlers. Event handlers are functions that will be notified when a certain event fires. These notifications optionally receive an event argument with details about the event (for example the x and y position of the mouse at a click event).
The observer pattern was the key idea behind events and delegates
Observer dofactory – link
Class code: observer – observing stock market – in Java!
The Mediator pattern provides central authority over a group of objects by encapsulating how these objects interact. This model is useful for scenarios where there is a need to manage complex conditions in which every object is aware of any state change in any other object in the group.
The Mediator patterns are useful in the development of complex forms. Take for example a page in which you enter options to make a flight reservation. A simple Mediator rule would be: you must enter a valid departure date, a valid return date, the return date must be after the departure date, a valid departure airport, a valid arrival airport, a valid number of travelers, and only then the Search button can be activated.
Another example of Mediator is of course a chat room when every message passes through a mediator which publishes only appropriate messages
Mediator dotnettutorials – chat room
Mediator dofactory – link
Class code: mediator – selling stocks – in Java!
More topics covered:
Links:
bridge iterator foreach yield

The Bridge pattern allows two components, a client and a service, to work together with each component having its own interface. Bridge is a high-level architectural pattern and its main goal is to write better code through two levels of abstraction. It facilitates very loose coupling of objects. It is sometimes referred to as a double Adapter pattern.
An example of the Bridge pattern is an application (the client) and a database driver (the service). The application writes to a well-defined database API, for example ODBC, but behind this API you will find that each driver’s implementation is totally different for each database vendor (SQL Server, MySQL, Oracle, etc.).
Bridge is very similar to strategy!
“They both look the same on the surface to me as well. The main difference I see is the fact that in the Bridge pattern, the abstraction is PART OF the object, but in the Strategy pattern the abstraction is performed BY the object.
Bridge: ( A structural pattern)
Bridge pattern decouples abstraction and implementation and allows both to vary independently.
Use this pattern when :
Strategy: ( Behavioural pattern)
Strategy patterns enable you to switch between multiple algorithms from a family of algorithms at run time.
Use Strategy pattern when :
The Iterator pattern allows clients to effectively loop over a collection of objects. A common programming task is to traverse and manipulate a collection of objects. These collections may be stored as an array or perhaps something more complex, such as a tree or graph structure. In addition, you may need to access the items in the collection in a certain order, such as, front to back, back to front, depth first (as in tree searches), skip evenly numbered objects, etc. The Iterator design pattern solves this problem by separating the collection of objects from the traversal of these objects by implementing a specialized iterator.
Today, many languages have Iterators built-in by supporting ‘for-each’-type constructs and IEnumerable and IEnumerator interfaces.



You use a yield return statement to return each element one at a time.
The sequence returned from an iterator method can be consumed by using a foreach statement or LINQ query. Each iteration of the foreach loop calls the iterator method. When a yield return statement is reached in the iterator method, expression is returned, and the current location in code is retained. Execution is restarted from that location the next time that the iterator function is called.
You can use a yield break statement to end the iteration.
… full article
nice article on yield
Class code: foreach yield
Youtube code: foreach yield list



The foreach statement executes a statement or a block of statements for each element in an instance of the type that contains GetEnumerator method. The foreach statement is not limited to those types and can be applied to an instance of any type that satisfies the following conditions:
GetEnumerator method whose return type is either class, struct, or interface typeGetEnumerator — which has public Current property, public parameterless MoveNext method whose return type is Boolean and public Reset(of course you can also implement System.Collections.IEnumerable or System.Collections.Generic.IEnumerable interfaces)
Class code: foreach a class using enumerator
Youtube code: foreach my data collection
More topics covered:
Links:
abstract-factory strategy log4net

The Strategy pattern encapsulates alternative algorithms (or strategies) for a particular task. It allows a method to be swapped out at runtime by any other method (strategy) without the client realizing it. Essentially, Strategy is a group of algorithms that are interchangeable.
Say we like to test the performance of different sorting algorithms to an array of numbers: shell sort, heap sort, bubble sort, quicksort, etc. Applying the Strategy pattern to these algorithms allows the test program to loop through all algorithms, simply by changing them at runtime and test each of these against the array. For Strategy to work all method signatures must be the same so that they can vary without the client program knowing about it.
Strategy dofactory – link
Class code: strategy demo in JAVA!
An Abstract Factory creates objects that are related by a common theme. In object-oriented programming a Factory is an object that creates other objects. An Abstract Factory has abstracted out a theme which is shared by the newly created objects.
Suppose we have two Abstract Factories whose task it is to create page controls, such as, buttons, textboxes, radio buttons, and listboxes. One is the Light Factory which creates controls that are white and the other the Dark Factory which creates controls that are black. Both Factories creates the same types of controls, but they differ in color, which is their common theme. This is an implementation of the Abstract Factory pattern.
This includes scenarios in which the creation process involves object caching, sharing or re-using of objects, complex logic, or applications that maintain object and type counts, and objects that interact with different resources or devices. If your application needs more control over the object creation process, consider using a Factory.
Abstract factory dofactory – link
Class code: abs factory demo in JAVA!
log4net is a tool to help the programmer output log statements to a variety of output targets. In case of problems with an application, it is helpful to enable logging so that the problem can be located. With log4net it is possible to enable logging at runtime without modifying the application binary. The log4net package is designed so that log statements can remain in production code without incurring a high performance cost. It follows that the speed of logging (or rather not logging) is crucial.
At the same time, log output can be so voluminous that it quickly becomes overwhelming. One of the distinctive features of log4net (and common to all of the log4x libraries) is the notion of hierarchical loggers. Using these loggers it is possible to selectively control which log statements are output at arbitrary granularity.
Apache log4net – home site!
Log4net appenders list
Log4net – demo project
Log4net – stackify demo!
formula: “AA,ABC@BC,DD@CDA”….
Json viewer stack.hu – click here
More topics covered:
Links:
chain-of-resp struct string-builder immutable

The Chain of Responsibility pattern provides a chain of loosely coupled objects one of which can satisfy a request. This pattern is essentially a linear search for an object that can handle a particular request.
An example of a chain-of-responsibility is event-bubbling in which an event propagates through a series of nested controls one of which may choose to handle the event.
Chain of resp. dofactory – link
Class code: chain of resp. demo in JAVA!
The in keyword causes arguments to be passed by reference. It makes the formal parameter an alias for the argument, which must be a variable. In other words, any operation on the parameter is made on the argument. It is like the ref or out keywords, except that in arguments cannot be modified by the called method. Whereas ref arguments may be modified, out arguments must be modified by the called method, and those modifications are observable in the calling context.

Mutable and immutable are English words that mean “can change” and “cannot change” respectively. The meaning of these words is the same in C# programming language; that means the mutable types are those whose data members can be changed after the instance is created but Immutable types are those whose data members can not be changed after the instance is created.
When we change the value of mutable objects, value is changed in same memory. But in immutable type, the new memory is created and the modified value is stored in new memory.
Let’s start with examples of predefined classes (String and StringBuilder)
A String is immutable, meaning String cannot be changed once created. For example, new string “Hello World!!” will occupy a memory space on the heap. Now, by changing the initial string “Hello World!!” to “Hello World!! from Tutorials Teacher” will create a new string object on the memory heap instead of modifying the initial string at the same memory address. This behaviour will hinder the performance if the same string changes multiple times by replacing, appending, removing or inserting new strings in the initial string.
To solve this problem, C# introduced StringBuilder. StringBuilder is a dynamic object that allows you to expand the number of characters in the string. It doesn’t create a new object in the memory but dynamically expands memory to accommodate the modified string
Structs share most of the same syntax as classes. The name of the struct must be a valid C# identifier name. Structs are more limited than classes in the following ways:
Dictionary<string, myStruct>.new operator.null, and a struct variable cannot be assigned null unless the variable is declared as a nullable value type.Value types and reference types are the two main categories of C# types. A variable of a value type contains an instance of the type. This differs from a variable of a reference type, which contains a reference to an instance of the type. By default, on assignment, passing an argument to a method, or returning a method result, variable values are copied. In the case of value-type variables, the corresponding type instances are copied
More topics covered:
Links:
visitor prototype extension methods

The Visitor pattern defines a new operation to a collection of objects without changing the objects themselves. The new logic resides in a separate object called the Visitor.
Visitors are useful when building extensibility in a library or framework. If the objects in your project provide a ‘visit’ method that accepts a Visitor object which can make changes to the receiving object then you are providing an easy way for clients to implement future extensions.
In most programming languages the Visitor pattern requires that the original developer anticipates functional adjustments in the future. This is done by including methods that accept a Visitor and let it operate on the original collection of objects.
Visitor dofactory – link
Class code: Visitor shapes and tax example
The Prototype Pattern creates new objects, but rather than creating non-initialized objects it returns objects that are initialized with values it copied from a prototype – or sample – object. The Prototype pattern is also referred to as the Properties pattern.
An example of where the Prototype pattern is useful is the initialization of business objects with values that match the default values in the database. The prototype object holds the default values that are copied over into a newly created business object.
Shallow copies duplicate as little as possible. A shallow copy of a collection is a copy of the collection structure, not the elements. With a shallow copy, two collections now share the individual elements.
Deep copies duplicate everything. A deep copy of a collection is two collections with all of the elements in the original collection duplicated.

Prototype dofactory – link
Class code: Prototype
see immutable and struct clone here in our blog – blog link
Extension methods enable you to “add” methods to existing types without creating a new derived type, recompiling, or otherwise modifying the original type. Extension methods are a special kind of static method, but they are called as if they were instance methods on the extended type. For client code written in C#, there is no apparent difference between calling an extension method and the methods that are actually defined in a type.
Class code: Extension methods example
Links:
proxy memento decorator nullable

The Proxy pattern provides a surrogate or placeholder object for another object and controls access to this other object.
In object-oriented programming, objects do the work they advertise through their interface (properties and methods). Clients of these objects expect this work to be done quickly and efficiently. However, there are situations where an object is severely constrained and cannot live up to its responsibility. Typically this occurs when there is a dependency on a remote resource (resulting in network latency) or when an object takes a long time to load.
In situations like these you apply the Proxy pattern and create a proxy object that ‘stands in’ for the original object. The Proxy forwards the request to a target object. The interface of the Proxy object is the same as the original object and clients may not even be aware they are dealing with a proxy rather than the real object
Proxy dofactory – link
Class code: Proxy ATM
Class code: Proxy for flight system
The Memento pattern provides temporary storage as well as restoration of an object. The mechanism in which you store the object’s state depends on the required duration of persistence, which may vary.
You could view a database as an implementation of the Memento design pattern in which objects are persisted and restored. However, the most common reason for using this pattern is to capture a snapshot of an object’s state so that any subsequent changes can be undone easily if necessary.
Essentially, a Memento is a small repository that stores an object’s state. Scenarios in which you may want to restore an object into a state that existed previously include: saving and restoring the state of a player in a computer game or the implementation of an undo operation in a database.
Proxy dofactory – link
Class code: Memento (winform)
A nullable value type T? represents all values of its underlying value type T and an additional null value. For example, you can assign any of the following three values to a bool? variable: true, false, or null. An underlying value type T cannot be a nullable value type itself.
Any nullable value type is an instance of the generic System.Nullable structure. You can refer to a nullable value type with an underlying type T in any of the following interchangeable forms: Nullable or T?.
You typically use a nullable value type when you need to represent the undefined value of an underlying value type. For example, a Boolean, or bool, variable can only be either true or false. However, in some applications a variable value can be undefined or missing. For example, a database field may contain true or false, or it may contain no value at all, that is, NULL. You can use the bool? type in that scenario.
nice idea: implement Nullable yourself using decorator pattern
see more on value type here in our blog – blog link
Links:
template-method proxy attributes

Attributes provide a powerful method of associating metadata, or declarative information, with code (assemblies, types, methods, properties, and so forth). After an attribute is associated with a program entity, the attribute can be queried at run time by using a technique called reflection
Attributes have the following properties:
Complete solution for query execution:
Links: