1/50
Looks like no tags are added yet.
What is Singleton?
A creational design pattern where a class controls its own creation, so only one object of that class can ever exist, and every part of the program shares that same object.
Example:
Your school has one registrar’s office. You don’t start your own registrar every time you need a transcript. You go to the registrar’s office.
Private constructor: you can’t just declare yourself a registrar.
One instance: there’s only one office holding the official records.
Global access point: everyone knows where it is and goes to the same place.
If there were two registrar’s offices with separate records, one could say you passed a class and the other could say you didn’t. That’s the kind of mess Singleton prevents in code. A logger, a settings manager, or a database connection pool should be one shared source of truth.
What is the motivation of a Singleton
Singleton ensures only one instance of a class can be created and provides a global access point to it.
What is the UML for Singleton?

What are the Singleton Participants?
_instance: Must be private and static
C’tor: Must be private so client code can’t “new”
GetInstance(): Must be public, static, to provide global access point
DLL
Dynamic Link Libraries. A file of compiled code that a program loads and uses while it runs, instead of having that code built into the program itself.
DLLs are linked at runtime, so many programs can share one copy and get fixes without recompiling.
Example: Open and Save As dialogs come from Windows’ comdlg32.dll. The other options describe a static library (.lib), and an executable (.exe).
What problem does a DLL solve?
Lets multiple programs reuse the same compiled code from one sperate file, so it can be shared, updated, and maintained without rebuilding every program that uses it.
Singleton Step 1: Create the class & Hide the constructor
namespace SingeltonDemo
{
internal class SingletonLogger
{
private SingletonLogger()
{
Console.WriteLine("In SingletonLogger ctor");
}
}
}Why: Marking the constructor private means only code inside the class can call new SingletonLogger(). If anyone outside tries it, they get a compile error. The class now controls its own creation. The Console.WriteLine is the “proof” line. Every time an object gets created, you’ll see it print. In a correct Singleton it prints only once.
Singleton Step 2: Hold the instance and handout the instance
namespace SingeltonDemo
{
internal class SingletonLogger
{
private static SingletonLogger _instance = null;
private SingletonLogger()
{
Console.WriteLine("In SingletonLogger ctor");
}
public static SingletonLogger GetInstance()
{
if (_instance == null)
{
_instance = new SingletonLogger();
}
return _instance;
}
}
}Inserted:
private static SingletonLogger _instance = null;
public static SingleLogger GetInstance() and the rest
The logic inside:
Check the shelf: if(_instance == null). Is it empty?
If empty, create it: _instance = new SingletonLogger();. This is allowed because we’re inside the class, so the private constructor is reachable. This happens only on the first call.
Hand it out: return _instance;. Every call, first or hundredth, returns the same object.
Singleton Step 3: Add the Class’s regular methods
namespace SingeltonDemo
{
internal class SingletonLogger
{
private static SingletonLogger _instance = null;
private SingletonLogger()
{
Console.WriteLine("In SingletonLogger ctor");
}
public static SingletonLogger GetInstance()
{
if(_instance == null)
{
_instance = new SingletonLogger();
}
return _instance;
}
public void Logging()
{
Console.WriteLine("SingletonLogger logging");
}
}
}Inserted:
public void Logging() and the rest
Singleton Step 4: Test in Main
Create program.cs file on the same solution
namespace SingletonDemo
{
internal class Program
{
static void Main(string[] args)
{
Console.WriteLine("In Main");
SingletonLogger s1 = SingletonLogger.GetInstance();
s1.Logging();
SingletonLogger s2 = SingletonLogger.GetInstance();
Console.WriteLine("s1: {0} s2: {1}", s1.GetHashCode(), s2.GetHashCode());
}
}
}If both has codes match and “In SingletonLogger ctor” prints only once, your Singleton works.
Thread
A single line of work running your program. A normal console app has one thread that starts in Main and runs top to bottom, one line at a time.
Example: When you type in Word, one thread takes each keystroke and puts the letter on the screen. That’s a single path of work: key pressed, letter appears, repeat.
Mulithreading
The ability of a program to run multiple threads at the same time, so it can do several tasks at once while all the threads share the same memory.
Example: While you type, Word is also doing other things at the same time:
Spell check: red squiggly lines appear under typos while you keep typing
AutoSave: your documents saves in the background without freezing the screen
Word count: the counter at the bottom updates live
What is _lock in threading?
A private static object used with the lock statement so that only one thread at a time can run a block of code. In a Singleton, it stops two threads from creating two instances at the same time
What is an abstract class?
An abstract class is a class that cannot be instantiated directly and serves as a blueprint for other classes to inherit from.
What is Template Method Design Pattern?
A base class method defines the steps of an algorithm in a fixed order, and subclasses fill in some of the steps without changing that order.
For example: “I’ve written the steps and their order. Some of the steps I’ll do myself, but certain ones will be done by my subclasses. They can change how those steps work, but not the order.”
What is the motivation for Template Method Design
TemplateMethod() defines the skeleton of an algorithm and delegates to subclasses to implement the algorithm steps
What is the UML for Template Method Design Pattern?

What are the participants of Template Method Design Pattern?
TemplateMethod() - is public and it defines the algorithm through protected pure virtual primitive operations
Subclasses - Implement the protected primitive operations
Template Method UML-to-code mapping
Abstract Template Method Class = Beverage
Public TemplateMethod() = BeverageTemplate()
PrimOp1() ... PrimOpN() = Brew(), AddCondiments() (the variable steps)
Fixed methods: private void BoilWater(),private void PourInCup()
Algorithm Step: BoilWater(), Brew(), PourInCup(), AddCondiments()
Subclass = Coffee, Tea
You will be writing code for Template Method Design Pattern.
Template Method Step 1: Create the abstract class and declare the primitive operations
namespace BeverageTemplates
{
public abstract class BeverageTemplate
{
protected abstract void Brew();
protected abstract void AddCondiments();
}
}Why: abstract means nobody can call new Beverage(). The steps that vary are protected abstract, so subclasses must implement them but outside code can’t call them directly.
Template Method UML-to-code mapping
Abstract Template Method Class = Beverage
Public TemplateMethod() = BeverageTemplate()
PrimOp1() ... PrimOpN() = Brew(), AddCondiments() (the variable steps)
Fixed methods: private void BoilWater(),private void PourInCup()
Algorithm Step: BoilWater(), Brew(), PourInCup(), AddCondiments()
Subclass = Coffee, Tea
Template Method Step 2: Add the fixed steps and the TemplateMethod
namespace BeverageTemplates
{
public abstract class BeverageTemplate
{
public BeverageTemplate()
{
BoilWater();
Brew();
PourInCup();
AddCondiments();
}
private void BoilWater() { Console.WriteLine("Boiling water"); }
private void PourInCup() { Console.WriteLine("Pouring into cup"); }
protected abstract void Brew();
protected abstract void AddCondiments();
}
}Inserted: BeverageTemplate(), BoilWater(), and PourInCup().
Why: BeverageTemplate() is the TemplateMethod. It’s public and not virtual, so subclasses can’t change the order. BoilWater() and PourInCup() are the same for every drink, so they’re implemented once here.
Template Method UML-to-code mapping
Abstract Template Method Class = BeverageTemplate
Public TemplateMethod() = BeverageTemplate()
PrimOp1() ... PrimOpN() = Brew(), AddCondiments() (the variable steps)
Fixed methods: private void BoilWater(),private void PourInCup()
Algorithm Step: BoilWater(), Brew(), PourInCup(), AddCondiments()
Subclass = Coffee, Tea
Template Method Step 3: Create the Coffee subclass and implement the primitive operations
namespace TemplateBeverage
{
class Coffee : BeverageTemplate
{
protected override void Brew()
{
Console.WriteLine("Dripping coffee through filter");
}
protected override void AddCondiments()
{
Console.WriteLine("Adding milk and sugar");
}
}
}Inserted: the whole Coffee class (it goes alongside BeverageTemplate, not inside it).
Why: Coffee fills in only the blanks. It never touches BeverageTemplate(), so the order stays locked.
Template Method UML-to-code mapping
Abstract Template Method Class = Beverage
Public TemplateMethod() = BeverageTemplate()
PrimOp1() ... PrimOpN() = Brew(), AddCondiments() (the variable steps)
Fixed methods: private void BoilWater(),private void PourInCup()
Algorithm Step: BoilWater(), Brew(), PourInCup(), AddCondiments()
Subclass = Coffee, Tea
Template Method Step 4: Create a second subclass (Tea)
namespace TemplateMethodDemo
{
class Tea : Beverage
{
protected override void Brew()
{
Console.WriteLine("Steeping tea bag");
}
protected override void AddCondiments()
{
Console.WriteLine("Adding lemon");
}
}
}Inserted: the whole Tea class.
Why: A second subclass proves the point. Same skeleton, different details, and Beverage didn’t change at all.
Template Method Step 5: Test in Main
namespace Beverage
{
internal class Program
{
static void Main(string[] args)
{
BeverageTemplate coffee = new Coffee();
Console.WriteLine();
BeverageTemplate tea = new Tea();
}
}
}Expected output:
Water is boiling!
Dripping coffee through filter
Now pouring
Adding milk and sugar
Water is boiling!
Dripping tea through filter
Now pouring
Adding lemonWhy: If “Boiling water” and “Pouring into cup” show up in the same spots for both drinks while the middle and last steps differ, your Template Method works.
What is interface in Strategy Design Pattern?
In Strategy, the interface is the rule every strategy has to follow.
What is the Strategy Design Pattern?
The Strategy design pattern defines a family of algorithms, encapsulate each one, and make them interchangeable. This pattern lets the algorithm vary independently from clients that use it.
Example: Picture paying at a store. The cashier needs one thing done: get paid. You can do that with cash, a card, or Apple Pay. The cashier doesn’t care which one you use. They just say “pay,” and whatever method you hand over does its own thing.
That’s Strategy:
The job: paying
The different ways to do it: cash, card, Apple Pay. Each one is a strategy.
The one who needs it done: the cashier. They’re the context.
The rule: every payment method has to work when the cashier says “pay.” That shared rule is the interface.
And the key part: you can switch. Card declined? Pull out cash. The cashier doesn’t change at all; only the strategy does.
What is the motivation for Strategy?
Encapsulates interchangeable behavior. Client uses delegation to select behavior
What is the UML for Strategy?

What are the participants for Strategy?
IStrategy encapsulates interchangeable algorithms
Aggregaton denotes delegation to choose algorithm
What is the difference between Template Method and Strategy?

What is Observer Design Pattern?
The Observer design pattern defines a one-to-many dependency between objects so that when one object changes state, all its dependents are notified and updated automatically.
Example: Think of a YouTube channel. The channel (the Subject) doesn’t message each viewer one by one by hand. Viewers subscribe (Attach), and when a new video drops, everyone subscribed gets a notification (Notify) and reacts in their own way (Update). Unsubscribe (Detach) and the pings stop. The channel never needs to know who its subscribers are or what they do with the notification.
What is the motivation for observer?
Defines a one to many dependency between objects so that when one object changes state, all its dependents are notified and update automatically.
What is the observer UML?

What are the participants for Observer?
Subject know its observers and provides an interface for attaching/detaching/notifying observers.
Observers Implement an UpDate() interface to keep its state consistent with the subject’s state.
What is Iterator Design Pattern?
The Iterator design pattern provides a way to access the elements of an aggregate object sequentially without exposing its underlying representation.
Example: Think of a TV remote’s “next channel” button. You don’t know (or care) how the TV stores its channel list: array, linked list, or something weird. You just press Next until there are no more channels. The remote is the Iterator, and the channel list is the Aggregate. Swap in a different remote (say, one that goes backwards) and the TV doesn’t change.
What is the motivation of Iterator?
Provide a way to access the elements of an aggregate object sequentially without exposing the underlying representation.
What is UML for Iterator?

What are the participants for Iterator?
Iterator defines an interface for accessing and traversing elements.
Concrete Iterator implements the iterator interface and keeps track of the current position.
Aggregate defines an interface for creating an Iterator object.
Concrete Aggregate implements the iterator creation to return an instance of the proper concrete iterator
What is Composite Design Pattern?
The Composite design pattern composes objects into tree structures to represent part-whole hierarchies. This pattern lets clients treat individual objects and compositions of objects uniformly.
Example: In PowerPoint, you can click one shape and drag it, or select ten shapes, hit Group, and drag them all as one. You can even group groups. The program doesn’t have a separate “move a shape” path and “move a group” path. Both respond to the same Move command, and a group just passes it down to everything inside it.
What is the motivation for Composite?
Compose objects into tree structures to represent part-whole hierarchies. Composite let’s clients treat individual objects and compositions uniformly.
Composite UML

Composite Participants
Component declares the interface for objects in the composition, implements default behavior for the interface common to all classes, and declares an interface for accessing and managing child components.
Leaf represents leaf objects in the composition and has no children.
Composite defines behavior for components having children, stores child components, and implements child related operations in the component's interface
What is motivation for Visitor?
Allows adding operations without changing the classes or elements on which it operates
What is the UML for Visitor?

What are the participants for Visitor?
Visitor declares a Visit operation for each class of ConcreteElement.
The operation′s name and signature identifies the class that sends the Visit request to the Visitor.
ConcreteVisitor implements each operation declared by the Visitor.
Element defines an Accept operation that takes a visitor as an argument.
What is the motivation for Decorator?
Attach additional responsibilities to an object dynamically. Decorator provides a flexible alternative to subclassing. (Wraps an object to provide to provide new behavior)
What is the UML for Decorator?

What are the participants for decorator?
AbstractComponent provides an interface for objects that can have repsonibilities added to them dynamically.
ConcreteComponent defines an object to which additional responsibilities can be attached.
Abstract Decorator maintains a reference to the Abstract Component, defines an interface that conforms to a the Abstract Component′s interface, and provides pass through functionality.
Concrete Decorator adds responsibilites to the Concrete Component.
What is the motivation for Factory Method?
Define an interface for an object, but let subclasses decide which class to instantiate. Factory Method lets a class defer instantiation to subclasses.
What is the UML for Factory Method?

What are the participants for Factory Method?
Product defines the interface of objects the Factory Method creates.
ConcreteProduct implements the Product Interface
Creator declares Factory Method, which returns an object of type Product.