This is Class 1 on a 6 week course I taught on Software Design Patterns.
This course provides an introduction into Design Patterns and delves into the Singleton Pattern.
Class based on "Head First Design Patterns."
Singleton Design Pattern - Creation PatternSeerat Malik
In software engineering, the singleton pattern is a software design pattern that restricts the instantiation of a class to one. This is useful when exactly one object is needed to coordinate actions across the system. The term comes from the mathematical concept of a singleton.
With Code in JAVA
Design Pattern: Factory Pattern
In Factory pattern, we create object without exposing the creation logic to the client and refer to newly created object using a common interface.
Blog Article: http://jyaasa.com/blog/factory-design-pattern-in-ruby/
in these slides i have explained the factory method design pattern. slides contains complete notes on this pattern from definition to implementation by code example.
Singleton Pattern (Sole Object with Global Access)Sameer Rathoud
This presentation provide information about the various implementation of singleton design pattern with there pros and cons. Programming language used for implementation is c#.
In these slides i have explained an important design pattern that is "singleton pattern".
slides includes everything required about it, from definition to implementation and also different ways to achieve it according to situation and requirements.
Here is how we can implement this using the Prototype pattern:
1. Define an abstract Car class with Clone() method
2. Define concrete classes like SportsCar, Sedan etc extending Car
3. Each car stores its design configuration as properties
4. Application maintains a registry of car prototypes
5. When user wants to copy, app clones the prototype and returns new instance
6. User can independently customize cloned car without affecting original
This allows dynamic object copying and meets the requirements. Prototype pattern helps avoid complex object creation and gives flexibility to user for experimenting with different designs efficiently.
The document provides an introduction and overview of design patterns. It defines design patterns as common solutions to recurring problems in software design. The document discusses the origin of design patterns in architecture, describes the four essential parts of a design pattern (name, problem, solution, consequences), and categorizes patterns into creational, structural, and behavioral types. Examples of commonly used patterns like Singleton and State patterns are also presented.
The Prototype pattern allows objects to copy or clone themselves rather than being instantiated, making dynamic object creation easier. It is used when you need to copy an existing object rather than creating a new instance of it, or when objects must have one of a limited set of configurations. With the Prototype pattern, a prototype declares an interface for cloning itself and concrete prototypes implement cloning. A client creates a new object by asking a prototype to clone itself, either as a shallow or deep copy.
The Composite pattern allows hierarchical tree structures to be composed of objects. It allows clients to treat individual objects and compositions of objects uniformly. In the given document, the Composite pattern is described for representing graphical objects in a drawing editor. Graphic is an abstract component class that represents both individual graphical primitives like lines and text as well as container graphics like pictures. This allows clients to treat both types of graphics uniformly. The pattern provides structure for composing objects into tree structures and defines roles like component, leaf, and composite. It offers benefits like simplifying client code and making it easy to add new component types.
Design patterns are optimized, reusable solutions to the programming problems that we encounter every day. A design pattern is not a class or a library that we can simply plug into our system; it's much more than that. It is a template that has to be implemented in the correct situation. It's not language-specific either. A good design pattern should be implementable in most—if not all—languages, depending on the capabilities of the language. Most importantly, any design pattern can be a double-edged sword— if implemented in the wrong place, it can be disastrous and create many problems for you. However, implemented in the right place, at the right time, it can be your savior.
Fragments allow modular sections of an activity's UI to be reused across activities and configurations. A fragment must be embedded in an activity and shares its lifecycle. Fragments can be added or removed dynamically at runtime and their transactions can be added to a back stack. Activities can combine multiple fragments to build a multi-pane UI on tablets and reuse fragments across activities on handsets. To create a fragment, subclass Fragment and move code from activities into fragment lifecycle methods.
Name : Prasoon Dadhich
USN : 1MS09IS069
CODE
#include <iostream>
using namespace std;
class Singleton
{
private:
static bool instanceFlag;
static Singleton *single;
Singleton()
{
//private constructor
}
public:
static Singleton* getInstance();
void method();
~Singleton()
{
instanceFlag = false;
}
};
bool Singleton::instanceFlag = false;
Singleton* Singleton::single = NULL;
Singleton* Singleton::getInstance()
{
if(! instanceFlag)
{
single = new Singleton();
instanceFlag = true;
return single;
}
else
{
return single;
}
}
void Singleton::method()
{
cout << "Method of the singleton class" << endl;
}
int main()
{
Singleton *sc1,*sc2;
sc1 = Singleton::getInstance();
sc1->method();
sc2 = Singleton::getInstance();
sc2->method();
return 0;
}
Explanation
If we create any object of this class then the static object (player) will be returned and assigned to the new object.
Finally only one object will be there. The point is not how many times something gets executed, the point is, that the work is done by a single instance of the the class. This is ensured by the class method Singleton::getInstance().
As you can see in the above code,Client can access any instance of the singleton only through the getInstance() method.Once an instance is created,the instanceFlag value becomes true and then any further objects pointers created will be given the reference to the same object that has been created.
Also,make sure you notice the presence of a private constructor.This ensures that no new objects of the class are created and that all the class pointers get the same reference to work on.
The document discusses JUnit 5, the next generation of the JUnit testing framework for Java. Key aspects include a new programming model using extensions, support for Java 8 features, and ways to migrate from earlier JUnit versions. The new framework consists of the JUnit Platform launcher, the JUnit Jupiter API for writing tests, and the JUnit Vintage engine for running JUnit 3 and 4 tests.
The Singleton pattern ensures that only one instance of a class is created, and provides a global access point to that instance. There are many objects that only need a single instance, such as thread pools, caches, and objects used for logging or managing preferences. The Singleton pattern solves problems that could occur from instantiating multiple instances of these objects, such as inconsistent behavior or wasted resources. It works by having a class define a static method that returns its sole instance, which is created the first time the method is called.
The document discusses the SOLID principles of object-oriented design:
1. The Single Responsibility Principle states that a class should have one, and only one, reason to change.
2. The Open-Closed Principle states that software entities should be open for extension but closed for modification. Behavior is changed through inheritance and composition rather than direct modification.
3. The Liskov Substitution Principle states that subclasses must behave in the same way as the base class so that the base class can be substituted wherever the subclass is expected.
4. The Interface Segregation Principle states that interfaces should be small and focused so that client classes do not depend on methods they do not use.
The Factory Method pattern defines an interface for creating objects but lets subclasses decide which class to instantiate. It provides a way to delegate object instantiation to subclasses. For example, a hotel front desk acts as a factory by creating the appropriate type of room object based on a customer's needs. The pattern involves a Creator class with a factory method that returns a Product object, while ConcreteCreator subclasses override the method to instantiate a ConcreteProduct. This decouples client code from the instantiation process and makes a system extensible to new product types.
What is Dependency Injection in Spring Boot | EdurekaEdureka!
YouTube Link: https://youtu.be/O9mqe53syGc
** Microservices Architecture Training: https://www.edureka.co/microservices-... **
This Edureka tutorial on "What is Dependency Injection" will give you an introduction to dependency injection and also show a practical implementation of dependency injection with Spring Boot.
In this PPT, you will learn the following:
What is Dependency Injection?
Inversion of Control
Types of Dependency Injection
Benefits of Dependency Injection
Implement Dependency Injection using Spring Boot
Follow us to never miss an update in the future.
YouTube: https://www.youtube.com/user/edurekaIN
Instagram: https://www.instagram.com/edureka_learning/
Facebook: https://www.facebook.com/edurekaIN/
Twitter: https://twitter.com/edurekain
LinkedIn: https://www.linkedin.com/company/edureka
Castbox: https://castbox.fm/networks/505?country=in
The document provides an introduction to Gradle, an open source build automation tool. It discusses that Gradle is a general purpose build system with a rich build description language based on Groovy. It supports "build-by-convention" and is flexible and extensible, with built-in plugins for Java, Groovy, Scala, web and OSGi. The presentation covers Gradle's basic features, principles, files and collections, dependencies, multi-project builds, plugins and reading materials.
Lecture 11 from the IAG0040 Java course in TTÜ.
See the accompanying source code written during the lectures: https://github.com/angryziber/java-course
Describes goods and bads of software architecture as well as common design patterns.
This document provides an introduction to React.js, including:
- React.js uses a virtual DOM for improved performance over directly manipulating the real DOM. Components are used to build up the UI and can contain state that updates the view on change.
- The Flux architecture is described using React with unidirectional data flow from Actions to Stores to Views via a Dispatcher. This ensures state changes in a predictable way.
- Setting up React with tools like Browserify/Webpack for module bundling is discussed, along with additional topics like PropTypes, mixins, server-side rendering and React Native.
The document discusses three design patterns: Singleton, Observer, and Factory. The Singleton pattern ensures that only one instance of a class can exist and provides a global access point. The Observer pattern defines a subscription mechanism so that multiple objects can be notified of changes to an object they are observing. The Factory pattern provides an interface for creating objects but leaves the concrete class unspecified. Real-world examples and implementations of each pattern are provided.
Microservices with Java, Spring Boot and Spring CloudEberhard Wolff
Spring Boot makes creating small Java application easy - and also facilitates operations and deployment. But for Microservices need more: Because Microservices are a distributed systems issues like Service Discovery or Load Balancing must be solved. Spring Cloud adds those capabilities to Spring Boot using e.g. the Netflix stack. This talks covers Spring Boot and Spring Cloud and shows how these technologies can be used to create a complete Microservices environment.
This document provides an overview of design patterns including their definition, utility, essential elements, and examples. It discusses creational patterns like singleton, factory, and builder. Structural patterns covered include adapter, proxy, and composite. Behavioral patterns like command and iterator are also introduced. The document is presented as a slideshow by Dr. Lilia Sfaxi on design patterns for software engineering.
This document provides an overview and explanation of React Hooks. It introduces common Hooks like useState, useEffect, useReducer, and custom hooks. useState is used to add local state to functional components. useEffect is similar to component lifecycle methods and lets you perform side effects. useReducer is an alternative to useState for managing state in a single object. Custom hooks let you extract reusable logic and share it without changing components. The document also includes a FAQ addressing questions about hooks and class components.
Angular 16 is the biggest release since the initial rollout of Angular, and it changes everything: Bye bye zones, change-detection, life-cycle, children-selectors, Rx and what not.
Recorded webinar based on these slides given by Yaron Biton, Misterbit Coding-Academy’s CTO, can be found at: https://www.youtube.com/watch?v=92K1fgPbku8
Coding-Academy offers advanced web-techs training and software development services: Top-rated Full-stack courses for Angular, React, Vue, Node, Modern architectures, etc. | Available top-notch on-demand-coders trough Misterbit technological solutions | Coding-Academy Bootcamp: Hundreds of employed full-stack developers every year | Anything web, end to end projects | Tech companies and startups | Consulting to management and dev teams | Workshops for managers and leaders.
This document discusses the facade design pattern. The facade pattern provides a simplified interface to a more complex subsystem. It decouples the subsystem from the client and makes the subsystem easier to use. A facade acts as a front-facing interface that hides the underlying complexities of the subsystem and delegates client requests to appropriate subsystem classes. This reduces dependencies between subsystems and promotes loose coupling. The facade pattern is useful for layering subsystems and simplifying access to them through a single interface.
This is Class 2 on a 6 week course I taught on Software Design Patterns.
This course discusses Strategy and Template pattern.
Class based on "Head First Design Patterns."
This document discusses the Model-View-Controller (MVC) pattern in the context of a DJ music application called DJView. It goes through multiple versions of the DJView code, refactoring it to better separate the model, view, and controller responsibilities according to MVC. The model manages the application data and logic. The view displays data and handles user input. The controller mediates between the model and view, updating the model based on user input and notifying the view of model changes.
The Composite pattern allows hierarchical tree structures to be composed of objects. It allows clients to treat individual objects and compositions of objects uniformly. In the given document, the Composite pattern is described for representing graphical objects in a drawing editor. Graphic is an abstract component class that represents both individual graphical primitives like lines and text as well as container graphics like pictures. This allows clients to treat both types of graphics uniformly. The pattern provides structure for composing objects into tree structures and defines roles like component, leaf, and composite. It offers benefits like simplifying client code and making it easy to add new component types.
Design patterns are optimized, reusable solutions to the programming problems that we encounter every day. A design pattern is not a class or a library that we can simply plug into our system; it's much more than that. It is a template that has to be implemented in the correct situation. It's not language-specific either. A good design pattern should be implementable in most—if not all—languages, depending on the capabilities of the language. Most importantly, any design pattern can be a double-edged sword— if implemented in the wrong place, it can be disastrous and create many problems for you. However, implemented in the right place, at the right time, it can be your savior.
Fragments allow modular sections of an activity's UI to be reused across activities and configurations. A fragment must be embedded in an activity and shares its lifecycle. Fragments can be added or removed dynamically at runtime and their transactions can be added to a back stack. Activities can combine multiple fragments to build a multi-pane UI on tablets and reuse fragments across activities on handsets. To create a fragment, subclass Fragment and move code from activities into fragment lifecycle methods.
Name : Prasoon Dadhich
USN : 1MS09IS069
CODE
#include <iostream>
using namespace std;
class Singleton
{
private:
static bool instanceFlag;
static Singleton *single;
Singleton()
{
//private constructor
}
public:
static Singleton* getInstance();
void method();
~Singleton()
{
instanceFlag = false;
}
};
bool Singleton::instanceFlag = false;
Singleton* Singleton::single = NULL;
Singleton* Singleton::getInstance()
{
if(! instanceFlag)
{
single = new Singleton();
instanceFlag = true;
return single;
}
else
{
return single;
}
}
void Singleton::method()
{
cout << "Method of the singleton class" << endl;
}
int main()
{
Singleton *sc1,*sc2;
sc1 = Singleton::getInstance();
sc1->method();
sc2 = Singleton::getInstance();
sc2->method();
return 0;
}
Explanation
If we create any object of this class then the static object (player) will be returned and assigned to the new object.
Finally only one object will be there. The point is not how many times something gets executed, the point is, that the work is done by a single instance of the the class. This is ensured by the class method Singleton::getInstance().
As you can see in the above code,Client can access any instance of the singleton only through the getInstance() method.Once an instance is created,the instanceFlag value becomes true and then any further objects pointers created will be given the reference to the same object that has been created.
Also,make sure you notice the presence of a private constructor.This ensures that no new objects of the class are created and that all the class pointers get the same reference to work on.
The document discusses JUnit 5, the next generation of the JUnit testing framework for Java. Key aspects include a new programming model using extensions, support for Java 8 features, and ways to migrate from earlier JUnit versions. The new framework consists of the JUnit Platform launcher, the JUnit Jupiter API for writing tests, and the JUnit Vintage engine for running JUnit 3 and 4 tests.
The Singleton pattern ensures that only one instance of a class is created, and provides a global access point to that instance. There are many objects that only need a single instance, such as thread pools, caches, and objects used for logging or managing preferences. The Singleton pattern solves problems that could occur from instantiating multiple instances of these objects, such as inconsistent behavior or wasted resources. It works by having a class define a static method that returns its sole instance, which is created the first time the method is called.
The document discusses the SOLID principles of object-oriented design:
1. The Single Responsibility Principle states that a class should have one, and only one, reason to change.
2. The Open-Closed Principle states that software entities should be open for extension but closed for modification. Behavior is changed through inheritance and composition rather than direct modification.
3. The Liskov Substitution Principle states that subclasses must behave in the same way as the base class so that the base class can be substituted wherever the subclass is expected.
4. The Interface Segregation Principle states that interfaces should be small and focused so that client classes do not depend on methods they do not use.
The Factory Method pattern defines an interface for creating objects but lets subclasses decide which class to instantiate. It provides a way to delegate object instantiation to subclasses. For example, a hotel front desk acts as a factory by creating the appropriate type of room object based on a customer's needs. The pattern involves a Creator class with a factory method that returns a Product object, while ConcreteCreator subclasses override the method to instantiate a ConcreteProduct. This decouples client code from the instantiation process and makes a system extensible to new product types.
What is Dependency Injection in Spring Boot | EdurekaEdureka!
YouTube Link: https://youtu.be/O9mqe53syGc
** Microservices Architecture Training: https://www.edureka.co/microservices-... **
This Edureka tutorial on "What is Dependency Injection" will give you an introduction to dependency injection and also show a practical implementation of dependency injection with Spring Boot.
In this PPT, you will learn the following:
What is Dependency Injection?
Inversion of Control
Types of Dependency Injection
Benefits of Dependency Injection
Implement Dependency Injection using Spring Boot
Follow us to never miss an update in the future.
YouTube: https://www.youtube.com/user/edurekaIN
Instagram: https://www.instagram.com/edureka_learning/
Facebook: https://www.facebook.com/edurekaIN/
Twitter: https://twitter.com/edurekain
LinkedIn: https://www.linkedin.com/company/edureka
Castbox: https://castbox.fm/networks/505?country=in
The document provides an introduction to Gradle, an open source build automation tool. It discusses that Gradle is a general purpose build system with a rich build description language based on Groovy. It supports "build-by-convention" and is flexible and extensible, with built-in plugins for Java, Groovy, Scala, web and OSGi. The presentation covers Gradle's basic features, principles, files and collections, dependencies, multi-project builds, plugins and reading materials.
Lecture 11 from the IAG0040 Java course in TTÜ.
See the accompanying source code written during the lectures: https://github.com/angryziber/java-course
Describes goods and bads of software architecture as well as common design patterns.
This document provides an introduction to React.js, including:
- React.js uses a virtual DOM for improved performance over directly manipulating the real DOM. Components are used to build up the UI and can contain state that updates the view on change.
- The Flux architecture is described using React with unidirectional data flow from Actions to Stores to Views via a Dispatcher. This ensures state changes in a predictable way.
- Setting up React with tools like Browserify/Webpack for module bundling is discussed, along with additional topics like PropTypes, mixins, server-side rendering and React Native.
The document discusses three design patterns: Singleton, Observer, and Factory. The Singleton pattern ensures that only one instance of a class can exist and provides a global access point. The Observer pattern defines a subscription mechanism so that multiple objects can be notified of changes to an object they are observing. The Factory pattern provides an interface for creating objects but leaves the concrete class unspecified. Real-world examples and implementations of each pattern are provided.
Microservices with Java, Spring Boot and Spring CloudEberhard Wolff
Spring Boot makes creating small Java application easy - and also facilitates operations and deployment. But for Microservices need more: Because Microservices are a distributed systems issues like Service Discovery or Load Balancing must be solved. Spring Cloud adds those capabilities to Spring Boot using e.g. the Netflix stack. This talks covers Spring Boot and Spring Cloud and shows how these technologies can be used to create a complete Microservices environment.
This document provides an overview of design patterns including their definition, utility, essential elements, and examples. It discusses creational patterns like singleton, factory, and builder. Structural patterns covered include adapter, proxy, and composite. Behavioral patterns like command and iterator are also introduced. The document is presented as a slideshow by Dr. Lilia Sfaxi on design patterns for software engineering.
This document provides an overview and explanation of React Hooks. It introduces common Hooks like useState, useEffect, useReducer, and custom hooks. useState is used to add local state to functional components. useEffect is similar to component lifecycle methods and lets you perform side effects. useReducer is an alternative to useState for managing state in a single object. Custom hooks let you extract reusable logic and share it without changing components. The document also includes a FAQ addressing questions about hooks and class components.
Angular 16 is the biggest release since the initial rollout of Angular, and it changes everything: Bye bye zones, change-detection, life-cycle, children-selectors, Rx and what not.
Recorded webinar based on these slides given by Yaron Biton, Misterbit Coding-Academy’s CTO, can be found at: https://www.youtube.com/watch?v=92K1fgPbku8
Coding-Academy offers advanced web-techs training and software development services: Top-rated Full-stack courses for Angular, React, Vue, Node, Modern architectures, etc. | Available top-notch on-demand-coders trough Misterbit technological solutions | Coding-Academy Bootcamp: Hundreds of employed full-stack developers every year | Anything web, end to end projects | Tech companies and startups | Consulting to management and dev teams | Workshops for managers and leaders.
This document discusses the facade design pattern. The facade pattern provides a simplified interface to a more complex subsystem. It decouples the subsystem from the client and makes the subsystem easier to use. A facade acts as a front-facing interface that hides the underlying complexities of the subsystem and delegates client requests to appropriate subsystem classes. This reduces dependencies between subsystems and promotes loose coupling. The facade pattern is useful for layering subsystems and simplifying access to them through a single interface.
This is Class 2 on a 6 week course I taught on Software Design Patterns.
This course discusses Strategy and Template pattern.
Class based on "Head First Design Patterns."
This document discusses the Model-View-Controller (MVC) pattern in the context of a DJ music application called DJView. It goes through multiple versions of the DJView code, refactoring it to better separate the model, view, and controller responsibilities according to MVC. The model manages the application data and logic. The view displays data and handles user input. The controller mediates between the model and view, updating the model based on user input and notifying the view of model changes.
This is Class 2 on a 6 week course I taught on Software Design Patterns.
This course goes over Simple Factory, Factory Method, and Abstract Factory.
Class based on "Head First Design Patterns."
This is Class 4 on a 6 week course I taught on Software Design Patterns.
This course goes over Command and Adapter pattern.
Class based on "Head First Design Patterns."
This is Class 5 on a 6 week course I taught on Software Design Patterns.
This course discusses the Observer and Decorator patterns.
Class based on "Head First Design Patterns."
This document discusses common PHP design patterns. It begins by defining design patterns and mentioning the "Gang of Four" design patterns book. It then proceeds to describe several design patterns in detail, including Factory, Singleton, Strategy, Command, Chain of Responsibility, Observer, MVC, Front Controller, Adapter, and Facade patterns. Other patterns are also briefly listed.
Your first 5 PHP design patterns - ThatConference 2012Aaron Saray
This document discusses 5 common PHP design patterns: Singleton, Factory, Observer, Decorator, and Strategy. For each pattern, it provides a brief definition, examples of when it may be used, and code samples demonstrating its implementation in PHP. The document aims to introduce PHP developers to fundamental design patterns in an accessible way and encourage applying these patterns to improve code organization and reusability. It also stresses that design patterns are language-agnostic solutions to recurring problems and have been used by developers for many years, even if unfamiliar to some PHP programmers.
The document discusses basic design principles including contrast, repetition, alignment, and proximity. It provides examples of how to apply each principle and emphasizes that design elements should not be placed arbitrarily, but rather have a visual connection. The document also discusses typography, design rules of thumb, principles of using type, and using color in a design, specifically the concepts of complementary, triad, split complement, and analogous colors.
The document discusses how PHP 5.3 changes the implementation of common design patterns like the Singleton pattern and Observer pattern through the use of anonymous functions. It provides code examples of implementing these patterns in PHP 4/5.0-5.2 versus PHP 5.3 using features like closures, late static binding, and __invoke(). The document also proposes building a dependency injection container in PHP 5.3 using anonymous functions to describe object creation without instantiating objects. This approach results in a simple yet fully-featured dependency injector implementation in around 40 lines of code.
An introduction to structural design patterns in object orientation. Suitable for intermediate to advanced computing students and those studying software engineering.
This document discusses design patterns and provides examples of the Singleton and Abstract Factory patterns. It begins with an introduction to design patterns, their purpose and history. It then discusses the Singleton pattern in detail using a logger example and describes how to implement it using lazy instantiation. It also covers the Abstract Factory pattern using real world examples of a kitchen and chefs. It compares how these patterns would be implemented in code versus real objects.
This document contains brief knowledge about the concept of "Singleton Class in Java". This is the best, I can come up with.
So, please go through it and if I have missed anything related to topic. Let me know. Thanks.
Construction Management in Developing Countries, Lecture 8, Project Pperation and Maintenance in Developing Countries, impediments in implementation of planned maintenance
Domain Driven Design (DDD) involves strategic design practices to develop a software model that closely represents the business domain. It focuses on bringing together domain experts and developers to develop a shared ubiquitous language. The domain is divided into subdomains and core domains, with the core domain being the most important to the business. Models are developed for each bounded context, which represents an explicit boundary within a subdomain. Following DDD results in software that makes more sense to both the business and technical aspects of the organization.
Domain Driven Design Development Spring PortfolioSrini Penchikala
The document discusses the benefits of exercise for mental health. Regular physical activity can help reduce anxiety and depression and improve mood and cognitive function. Exercise causes chemical changes in the brain that may help alleviate symptoms of mental illness and boost overall mental well-being.
Structural Design Patterns: Adapter
The Adapter pattern converts the interface of an existing class into another interface clients expect. An adapter allows classes to work together that couldn't otherwise due to incompatible interfaces. There are two types of adapters - class adapters inherit from an existing class, while object adapters compose existing classes. The adapter pattern is useful when you need to use an existing class but its interface does not match what is needed.
003 obf600105 gpon ma5608 t basic operation and maintenance v8r15 issue1.02 (...Cavanghetboi Cavangboihet
This document provides a summary of the basic operations and maintenance of the GPON system from Huawei Technologies. It describes how to set up the maintenance environment, use command line features, perform system basic operations and maintenance, configure network management, and set up management security. Key topics covered include user account management, system configuration, hardware operation, and system maintenance.
As a guest speaker in NCU, I gave a talk about some best practices of JavaScript programming to college students. It covers basic JavaScript elements and some common pitfalls while dealing with asynchronous programming.
The document discusses object-oriented programming (OOP) principles and design patterns. It explains that OOP models real-world objects and their relationships, and outlines key OOP concepts like encapsulation, inheritance, abstraction, and polymorphism. It then discusses common design patterns like creational patterns (factory method, abstract factory, builder, prototype, singleton), structural patterns (adapter, bridge, composite, decorator, facade, flyweight, proxy), and behavioral patterns (chain of responsibility, command, interpreter, observer, state, visitor).
Jump start to OOP, OOAD, and Design PatternNishith Shukla
The document discusses object-oriented programming (OOP) and design patterns. It explains why software development benefits from modeling objects after real-world objects. Some key principles of OOP include encapsulation, inheritance, abstraction, and polymorphism. Common design patterns are also outlined, such as creational patterns like factory and prototype patterns, and structural patterns like adapter and bridge patterns.
The document discusses design patterns, including their definition, benefits, common myths, design principles, basic elements, categories, and the pattern life cycle. It provides examples of the Singleton and Observer patterns, and discusses how the Model-View-Controller pattern uses strategies like Observer, Strategy, and Composite. Experts recommend focusing on simplicity, practical extensibility over hypothetical generality, and adapting patterns to problems rather than following them rigidly.
This document discusses several design patterns including Iterator, Adapter, Singleton, and Flyweight. It provides descriptions of each pattern, including when they should be used and how they work. The Iterator pattern provides a standard way to access elements of a collection. The Adapter pattern allows incompatible interfaces to work together. The Singleton pattern ensures that only one instance of a class can exist. The Flyweight pattern reduces memory usage by sharing instances for identical object states. Design patterns provide reusable solutions to common programming problems and improve code design, documentation and collaboration between developers.
The document provides an introduction to design patterns developed by the Gang of Four (GoF). It discusses several common design patterns in JavaScript like the constructor pattern, module pattern, singleton pattern, observer pattern, mediator pattern, prototype pattern, command pattern, facade pattern, and mixin pattern. For each pattern, it explains the problem it addresses, provides an example implementation, and notes advantages and disadvantages of the pattern. The overall document serves as a high-level overview of fundamental design patterns and their usage in JavaScript applications.
Design patterns provide common templates for solving similar problems. They also provide a higher-level language for software developers to use to describe approaches they might choose when designing part of an application. This session introduces and applies several patterns useful to web application developers. Examples will primarily use C#/.NET.
This document discusses design patterns, which are standard solutions to common problems in software design. It defines design patterns and provides examples of different categories of patterns, including creational patterns like Factory Method and Singleton, and structural patterns like Adapter and Facade. For each pattern, it describes the problem, solution, example use cases, and implementations in Java frameworks. Benefits of design patterns include enabling large-scale reuse and making expert knowledge widely available, while drawbacks can include potential for pattern overload.
This document discusses design patterns and provides examples of implementing some common patterns in C#. It begins with an introduction to design patterns, their history and types. It then demonstrates implementing singleton, prototype, facade and decorator patterns in C#, including class diagrams and implementation steps. It discusses advantages of design patterns and hints for advanced development, like making patterns thread-safe. The document concludes with a thank you.
1. Using finalizers in .NET is generally not recommended due to various issues and downsides they introduce.
2. Finalizers are not guaranteed to run deterministically and can cause objects to remain in memory longer than needed, hurting performance.
3. They run on a separate thread, so new object creation may outpace finalizer execution, risking out of memory errors over time. Any exceptions in a finalizer will crash the application.
The document provides an overview of unit testing and dependency injection using Entity Framework. It discusses how to achieve true unit testing through dependency injection and mocking dependencies. It provides examples of how to set up interfaces, manager classes, context classes and writing unit tests using Rhino Mocks and MSTest. Code coverage is also discussed as an important part of unit testing.
Creational patterns deal with object creation and aim to create objects in a suitable manner. There are three main creational patterns: the factory pattern, which provides a consistent interface for creating properly configured objects; the abstract factory pattern, which is a factory for factories and handles more complex situations; and the singleton pattern, which ensures a single instance of an object and consistency of data by restricting object instantiation.
This document provides an introduction to design patterns, including their motivation, history, definition, categories, and examples. Some key points:
- Design patterns solve common programming problems by describing reusable solutions that can be adapted for different situations.
- Common categories include creational, structural, and behavioral patterns. Example patterns discussed are Singleton, Decorator, Abstract Factory.
- Design patterns speed up development, promote code reuse, and make software more robust, maintainable and extensible. Resources for further information on design patterns are provided.
This document introduces several design patterns including abstract factory, singleton, prototype, adapter, composite, and decorator patterns. It provides examples of how each pattern works and why it would be used, with accompanying PHP code samples. Design patterns are general reusable solutions to common programming problems and help show the relationship and interaction between objects.
The document discusses several creational design patterns including Singleton, Abstract Factory, Builder, and Prototype patterns. It provides definitions and examples of how each pattern works, including ensuring a class only has one instance (Singleton), creating object factories without specifying classes (Abstract Factory), constructing complex objects step-by-step (Builder), and copying existing objects (Prototype). The document is intended for teaching software design patterns to students.
This document discusses several common JavaScript design patterns including Singleton, Factory, Module, Decorator, Command, and Observer patterns. It provides descriptions and code examples for each pattern. The Singleton pattern ensures a class only has one instance and provides a global access point. Factory patterns are used for object creation. The Module pattern provides private and public encapsulation for classes. The Decorator pattern attaches additional responsibilities to objects dynamically. The Command pattern encapsulates requests as objects, and the Observer pattern allows objects to watch other objects for changes.
The document discusses best practices for developing jQuery plugins. It covers defining a private scope, using a template, understanding the plugin syntax, adding options through object literals, and iterating through matched elements using this.each(). The key steps are to make the plugin easy to use, use good naming conventions, define a closure, set default parameters, allow chaining by returning this, document the code, and thoroughly test the plugin.
what is design pattern?
what is design pattern in java?
what are the classification of design pattern?
why design pattern is important?
how we can implement any design pattern?
example of design pattern.
Presented at NDC 2014 in Oslo (4th June 2014)
Video available on Vimeo: https://vimeo.com/97344527
Apparently, everyone knows about patterns. Except for the ones that don't. Which is basically all the people who've never come across patterns... plus most of the people who have.
Singleton is often treated as a must-know pattern. Patterns are sometimes considered to be the basis of blueprint-driven architecture. Patterns are also seen as something you don't need to know any more because you've got frameworks, libraries and middleware by the download. Or that patterns are something you don't need to know because you're building on UML, legacy code or emergent design. There are all these misconceptions about patterns... and more.
In this talk, let's take an alternative tour of patterns, one that is based on improving the habitability of code, communication, exploration, empiricism, reasoning, incremental development, sharing design and bridging rather than barricading different levels of expertise.
#StandardsGoals for 2025: Standards & certification roundup - Tech Forum 2025BookNet Canada
Book industry standards are evolving rapidly. In the first part of this session, we’ll share an overview of key developments from 2024 and the early months of 2025. Then, BookNet’s resident standards expert, Tom Richardson, and CEO, Lauren Stewart, have a forward-looking conversation about what’s next.
Link to recording, transcript, and accompanying resource: https://bnctechforum.ca/sessions/standardsgoals-for-2025-standards-certification-roundup/
Presented by BookNet Canada on May 6, 2025 with support from the Department of Canadian Heritage.
Spark is a powerhouse for large datasets, but when it comes to smaller data workloads, its overhead can sometimes slow things down. What if you could achieve high performance and efficiency without the need for Spark?
At S&P Global Commodity Insights, having a complete view of global energy and commodities markets enables customers to make data-driven decisions with confidence and create long-term, sustainable value. 🌍
Explore delta-rs + CDC and how these open-source innovations power lightweight, high-performance data applications beyond Spark! 🚀
UiPath Community Berlin: Orchestrator API, Swagger, and Test Manager APIUiPathCommunity
Join this UiPath Community Berlin meetup to explore the Orchestrator API, Swagger interface, and the Test Manager API. Learn how to leverage these tools to streamline automation, enhance testing, and integrate more efficiently with UiPath. Perfect for developers, testers, and automation enthusiasts!
📕 Agenda
Welcome & Introductions
Orchestrator API Overview
Exploring the Swagger Interface
Test Manager API Highlights
Streamlining Automation & Testing with APIs (Demo)
Q&A and Open Discussion
Perfect for developers, testers, and automation enthusiasts!
👉 Join our UiPath Community Berlin chapter: https://community.uipath.com/berlin/
This session streamed live on April 29, 2025, 18:00 CET.
Check out all our upcoming UiPath Community sessions at https://community.uipath.com/events/.
Special Meetup Edition - TDX Bengaluru Meetup #52.pptxshyamraj55
We’re bringing the TDX energy to our community with 2 power-packed sessions:
🛠️ Workshop: MuleSoft for Agentforce
Explore the new version of our hands-on workshop featuring the latest Topic Center and API Catalog updates.
📄 Talk: Power Up Document Processing
Dive into smart automation with MuleSoft IDP, NLP, and Einstein AI for intelligent document workflows.
What is Model Context Protocol(MCP) - The new technology for communication bw...Vishnu Singh Chundawat
The MCP (Model Context Protocol) is a framework designed to manage context and interaction within complex systems. This SlideShare presentation will provide a detailed overview of the MCP Model, its applications, and how it plays a crucial role in improving communication and decision-making in distributed systems. We will explore the key concepts behind the protocol, including the importance of context, data management, and how this model enhances system adaptability and responsiveness. Ideal for software developers, system architects, and IT professionals, this presentation will offer valuable insights into how the MCP Model can streamline workflows, improve efficiency, and create more intuitive systems for a wide range of use cases.
Linux Support for SMARC: How Toradex Empowers Embedded DevelopersToradex
Toradex brings robust Linux support to SMARC (Smart Mobility Architecture), ensuring high performance and long-term reliability for embedded applications. Here’s how:
• Optimized Torizon OS & Yocto Support – Toradex provides Torizon OS, a Debian-based easy-to-use platform, and Yocto BSPs for customized Linux images on SMARC modules.
• Seamless Integration with i.MX 8M Plus and i.MX 95 – Toradex SMARC solutions leverage NXP’s i.MX 8 M Plus and i.MX 95 SoCs, delivering power efficiency and AI-ready performance.
• Secure and Reliable – With Secure Boot, over-the-air (OTA) updates, and LTS kernel support, Toradex ensures industrial-grade security and longevity.
• Containerized Workflows for AI & IoT – Support for Docker, ROS, and real-time Linux enables scalable AI, ML, and IoT applications.
• Strong Ecosystem & Developer Support – Toradex offers comprehensive documentation, developer tools, and dedicated support, accelerating time-to-market.
With Toradex’s Linux support for SMARC, developers get a scalable, secure, and high-performance solution for industrial, medical, and AI-driven applications.
Do you have a specific project or application in mind where you're considering SMARC? We can help with Free Compatibility Check and help you with quick time-to-market
For more information: https://www.toradex.com/computer-on-modules/smarc-arm-family
HCL Nomad Web – Best Practices und Verwaltung von Multiuser-Umgebungenpanagenda
Webinar Recording: https://www.panagenda.com/webinars/hcl-nomad-web-best-practices-und-verwaltung-von-multiuser-umgebungen/
HCL Nomad Web wird als die nächste Generation des HCL Notes-Clients gefeiert und bietet zahlreiche Vorteile, wie die Beseitigung des Bedarfs an Paketierung, Verteilung und Installation. Nomad Web-Client-Updates werden “automatisch” im Hintergrund installiert, was den administrativen Aufwand im Vergleich zu traditionellen HCL Notes-Clients erheblich reduziert. Allerdings stellt die Fehlerbehebung in Nomad Web im Vergleich zum Notes-Client einzigartige Herausforderungen dar.
Begleiten Sie Christoph und Marc, während sie demonstrieren, wie der Fehlerbehebungsprozess in HCL Nomad Web vereinfacht werden kann, um eine reibungslose und effiziente Benutzererfahrung zu gewährleisten.
In diesem Webinar werden wir effektive Strategien zur Diagnose und Lösung häufiger Probleme in HCL Nomad Web untersuchen, einschließlich
- Zugriff auf die Konsole
- Auffinden und Interpretieren von Protokolldateien
- Zugriff auf den Datenordner im Cache des Browsers (unter Verwendung von OPFS)
- Verständnis der Unterschiede zwischen Einzel- und Mehrbenutzerszenarien
- Nutzung der Client Clocking-Funktion
Big Data Analytics Quick Research Guide by Arthur MorganArthur Morgan
This is a Quick Research Guide (QRG).
QRGs include the following:
- A brief, high-level overview of the QRG topic.
- A milestone timeline for the QRG topic.
- Links to various free online resource materials to provide a deeper dive into the QRG topic.
- Conclusion and a recommendation for at least two books available in the SJPL system on the QRG topic.
QRGs planned for the series:
- Artificial Intelligence QRG
- Quantum Computing QRG
- Big Data Analytics QRG
- Spacecraft Guidance, Navigation & Control QRG (coming 2026)
- UK Home Computing & The Birth of ARM QRG (coming 2027)
Any questions or comments?
- Please contact Arthur Morgan at [email protected].
100% human made.
The Evolution of Meme Coins A New Era for Digital Currency ppt.pdfAbi john
Analyze the growth of meme coins from mere online jokes to potential assets in the digital economy. Explore the community, culture, and utility as they elevate themselves to a new era in cryptocurrency.
AI and Data Privacy in 2025: Global TrendsInData Labs
In this infographic, we explore how businesses can implement effective governance frameworks to address AI data privacy. Understanding it is crucial for developing effective strategies that ensure compliance, safeguard customer trust, and leverage AI responsibly. Equip yourself with insights that can drive informed decision-making and position your organization for success in the future of data privacy.
This infographic contains:
-AI and data privacy: Key findings
-Statistics on AI data privacy in the today’s world
-Tips on how to overcome data privacy challenges
-Benefits of AI data security investments.
Keep up-to-date on how AI is reshaping privacy standards and what this entails for both individuals and organizations.
Increasing Retail Store Efficiency How can Planograms Save Time and Money.pptxAnoop Ashok
In today's fast-paced retail environment, efficiency is key. Every minute counts, and every penny matters. One tool that can significantly boost your store's efficiency is a well-executed planogram. These visual merchandising blueprints not only enhance store layouts but also save time and money in the process.
Dev Dives: Automate and orchestrate your processes with UiPath MaestroUiPathCommunity
This session is designed to equip developers with the skills needed to build mission-critical, end-to-end processes that seamlessly orchestrate agents, people, and robots.
📕 Here's what you can expect:
- Modeling: Build end-to-end processes using BPMN.
- Implementing: Integrate agentic tasks, RPA, APIs, and advanced decisioning into processes.
- Operating: Control process instances with rewind, replay, pause, and stop functions.
- Monitoring: Use dashboards and embedded analytics for real-time insights into process instances.
This webinar is a must-attend for developers looking to enhance their agentic automation skills and orchestrate robust, mission-critical processes.
👨🏫 Speaker:
Andrei Vintila, Principal Product Manager @UiPath
This session streamed live on April 29, 2025, 16:00 CET.
Check out all our upcoming Dev Dives sessions at https://community.uipath.com/dev-dives-automation-developer-2025/.
HCL Nomad Web – Best Practices and Managing Multiuser Environmentspanagenda
Webinar Recording: https://www.panagenda.com/webinars/hcl-nomad-web-best-practices-and-managing-multiuser-environments/
HCL Nomad Web is heralded as the next generation of the HCL Notes client, offering numerous advantages such as eliminating the need for packaging, distribution, and installation. Nomad Web client upgrades will be installed “automatically” in the background. This significantly reduces the administrative footprint compared to traditional HCL Notes clients. However, troubleshooting issues in Nomad Web present unique challenges compared to the Notes client.
Join Christoph and Marc as they demonstrate how to simplify the troubleshooting process in HCL Nomad Web, ensuring a smoother and more efficient user experience.
In this webinar, we will explore effective strategies for diagnosing and resolving common problems in HCL Nomad Web, including
- Accessing the console
- Locating and interpreting log files
- Accessing the data folder within the browser’s cache (using OPFS)
- Understand the difference between single- and multi-user scenarios
- Utilizing Client Clocking
Complete Guide to Advanced Logistics Management Software in Riyadh.pdfSoftware Company
Explore the benefits and features of advanced logistics management software for businesses in Riyadh. This guide delves into the latest technologies, from real-time tracking and route optimization to warehouse management and inventory control, helping businesses streamline their logistics operations and reduce costs. Learn how implementing the right software solution can enhance efficiency, improve customer satisfaction, and provide a competitive edge in the growing logistics sector of Riyadh.
2. Agenda Introduction to Design Patterns What is a Design Pattern Why Study Design Patterns History of Design Patterns The Gang of Four Tangent: Unit Testing The Book: Head First Design Patterns The Singleton Pattern Logger Example Lazy Instantiation Singleton vs. Static Variables Threading: Simple, Double-Checked, Eager Initialization Lab Inheritance Add Registry to Singleton Dependencies Unit Testing Articles
3. What is a Design Pattern? A problem that someone has already solved. A model or design to use as a guide More formally: “A proven solution to a common problem in a specified context." Real World Examples Blueprint for a house Manufacturing 05/27/10
4. Why Study Design Patterns? Provides software developers a toolkit for handling problems that have already been solved. Provides a vocabulary that can be used amongst software developers. The Pattern Name itself helps establish a vocabulary Helps you think about how to solve a software problem. 05/27/10
5. History of Design Patterns Christopher Alexander (Civil Engineer) in 1977 wrote “ Each pattern describes a problem which occurs over and over again in our environment, and then describes the core of the solution to that problem, in such a way that you can use this solution a million times over, without ever doing it the same way twice .” Each pattern has the same elements Pattern Name – helps develop a catalog of common problems Problem – describes when to apply the pattern. Describes problem and its context. Solution – Elements that make up the design, their relationships, responsibilities, and collaborations. Consequences – Results and trade-offs of applying the pattern 05/27/10
6. History (continued) In 1995, the principles that Alexander established were applied to software design and architecture. The result was the book: “ Design Patterns: Elements of Reusable Object-Oriented Software” by Erich Gamma, Richard Helm, Ralph Johnson, and John Vlissides. Also commonly known as “The Gang of Four”. 05/27/10
7. The Gang of Four Defines a Catalog of different design patterns. Three different types Creational – “creating objects in a manner suitable for the situation” Structural – “ease the design by identifying a simple way to realize relationships between entities” Behavorial – “common communication patterns between objects” 05/27/10
8. The Gang of Four: Pattern Catalog 05/27/10 Patterns in red will be discussed in class. Creational Abstract Factory Builder Factory Method Prototype Singleton Structural Adapter Bridge Composite Decorator Façade Flyweight Proxy Behavioral Chain of Responsibility Command Interpreter Iterator Mediator Memento Observer State Strategy Template Method Visitor
9. How Design Patterns Solve Design Problems From Gang of Four. Finding Appropriate Objects Determine Object Granularity Specify Object Interfaces Specifying Object Implementations Programming to an Interface, not an Implementation Encourage Reusability Inheritance versus Composition Delegation Support Extensibility Frameworks 05/27/10
10. Reality Problems with design early on It is sometimes very hard to “see” a design pattern. Not all requirements are known. A design that is applicable early on becomes obsolete. “ Paralysis by Analysis” Due to these realities, refactoring is inevitable! Question: How do you mitigate the fact that you won’t have all of the design figured out? 05/27/10
11. Tangent: Unit Testing If you create unit tests early in the development cycle, then it will be easier to refactor later on when more requirements are known. As a developer, you will have more confidence to make good design adjustments. Good design adjustments may lead to better maintainability of the code! What happens if you do not have Unit Tests early on? These statements may be heard: “ I am afraid to breaking something.” “ I know the right thing to do….but I am not going to do it because the system may become unstable.” You may incur “Technical Debt” if you do not refactor well 05/27/10
12. Unit Testing (cont) Unit Testing leads to easier Refactoring With easier Refactoring, you can take the risk of applying Design Patterns, even if it means changing a lot of code. Applying Design Patterns can decrease Technical Debt and improve the maintainability and extendibility of your system. Therefore…it pays to Unit Test! 05/27/10
13. Unit Testing: Final Thoughts Make unit testing part of the project culture. When creating a schedule, include unit testing in your estimates. Create your unit tests before you write the code. This helps define “Doneness” Helps you think about how software needs to be layered…it may actually lead to more refactoring! 05/27/10
14. Common Pitfall “ I just learned about Design Pattern XYZ. Let’s use it!” Reality : If you are going to use a Design Pattern, you should have a reason to do so. The software requirements should really drive why you are going to use (or not use) a Design Pattern. 05/27/10
15. The Book “ Head First Design Patterns” Eric Freeman & Elisabeth Freeman Book is based on the Gang of Four design patterns. Easier to read. Examples are fun, but not necessarily “real world”. 05/27/10
16. Example: Logger What is wrong with this code? public class Logger { public Logger() { } public void LogMessage() { //Open File "log.txt" //Write Message //Close File } }
17. Example: Logger (cont) Since there is an external Shared Resource (“log.txt”), we want to closely control how we communicate with it. We shouldn’t have to create the Logger class every time we want to access this Shared Resource. Is there any reason to? We need ONE.
18. Singleton GoF Definition: “The Singleton Pattern ensures a class has only one instance , and provides a global point of access to it.” Best Uses Logging Caches Registry Settings Access External Resources Printer Device Driver Database 05/27/10
19. Logger – as a Singleton public class Logger { private Logger{} private static Logger uniqueInstance; public static Logger getInstance() { if (uniqueInstance == null) uniqueInstance = new Logger(); return uniqueInstance; } } 05/27/10 Note the parameterless constructor See pg 173 in book
20. Lazy Instantiation Objects are only created when it is needed Helps control that we’ve created the Singleton just once. If it is resource intensive to set up, we want to do it once. 05/27/10
21. Singleton vs. Static Variables What if we had not created a Singleton for the Logger class?? Let’s pretend the Logger() constructor did a lot of setup. In our main program file, we had this code: public static Logger MyGlobalLogger = new Logger(); All of the Logger setup will occur regardless if we ever need to log or not.
22. Threading public class Singleton { private Singleton() {} private static Singleton uniqueInstance; public static Singleton getInstance() { if (uniqueInstance == null) uniqueInstance = new Singleton(); return uniqueInstance; } } 05/27/10 What would happen if two different threads accessed this line at the same time?
23. Option #1: Simple Locking public class Singleton { private Singleton() {} private static Singleton uniqueInstance; public static Singleton getInstance() { synchronized(Singleton.class) { if (uniqueInstance == null) uniqueInstance = new Singleton(); } return uniqueInstance; } }
24. Option #2 – Double-Checked Locking public class Singleton { private Singleton() {} private volatile static Singleton uniqueInstance; public static Singleton getInstance() { if (uniqueInstance == null) { synchronized(Singleton.class) { if (uniqueInstance == null) uniqueInstance = new Singleton(); } } return uniqueInstance; } } pg 182
25. Option #2 (C# Example) public class Singleton { private Singleton() {} private static object syncRoot = new Object(); private static volatile Singleton instance; public static Singleton Instance { get { if (instance == null) //first check { lock (syncRoot) { if (instance == null) //second check instance = new Singleton(); } } return instance; } } } 05/27/10
26. Option #3: “Eager” Initialization public class Singleton { private Singleton() {} private static Singleton uniqueInstance = new Singleton() public static Singleton getInstance() { return uniqueInstance; } } 05/27/10 Instance is created the first time any member of the class is referenced. Good to use if the application always creates; and if little overhead to create. Runtime guarantees that this is thread-safe pg 181
27. Lab #1: Turn a class into a Singleton public class Logger { public Logger() { } public void WriteLine(string text) { } public string ReadEntireLog() { return “Log Entries Here”; } } 05/27/10 Take this class and turn it into a Singleton.
28. Lab #1 Answer public class Logger { private Logger() { } private static Logger instance; public static Logger getInstance() { if (instance == null) instance = new Logger(); return instance; } //Functions . . .
29. Lab #2 public class BaseSingleton { private BaseSingleton() { } private static BaseSingleton instance; public static BaseSingleton getInstance() { if (instance == null) { instance = new BaseSingleton(); } return instance; } //Some state variables protected int someInt; //Function is marked as virtual so that it can be overidden public void DoSomething() { someInt = 1; } } 05/27/10
30. Lab #2 (cont) public class SubClassSingleton extends BaseSingleton { private SubClassSingleton() { } public void DoSomething() { someInt = 2; } public void NewFunction() { //new functionality here } } 05/27/10
31. Lab #2 (cont) Question #1: What is wrong with the constructor for SubClassSingleton? 05/27/10
32. Lab #2 (cont) Here is the code that calls the Singleton: public class Main { public static void DoStuff() { 01 BaseSingleton.getInstance().DoSomething(); 02 SubClassSingleton.getInstance().DoSomething(); 03 SubClassSingleton.getInstance().NewFunction(); } } 05/27/10
33. Lab #2 (cont) Question #2: For Line 01, what is the value of someInt after it is called? Question #3: For Line 02, what is the value of someInt after it is called? Question #4: What is wrong with Line 03? 05/27/10
34. Lab #2 Answers Question #1 : It will not compile. The base constructor must be changed from private to protected. Question #2 – 1 Question #3 - 1 Even though we have overridden the base, it doesn’t matter. The base implementation is returned by getInstance(). Question 4 – It will not compile!
35. Inheritance Summary The sub-class can share state with the base class. Now you have two objects that share state. “ Gang of Four” recommends usages of a registry of Singletons. The base class reads an environment variable to determine which Singleton to use. Bottom Line : Singletons and Inheritance do not mix well. 05/27/10
36. Add Registry to Singleton public class BaseSingleton { protected BaseSingleton() { } private static HashMap map = new HashMap(); public static BaseSingleton getInstance(String classname) { //First, attempt to get Singleton from HashMap BaseSingleton singleton = (BaseSingleton)map.get(classname); if (singleton != null) return singleton; else { //Singleton not found if (classname.Equals("SubClassSingleton")) singleton = new SubClassSingleton(); else ...... //Add singleton to HashMap so we can get it again map.put(classname, singleton); return singleton; }
37. SingletonRegistry Class Source http://www.javaworld.com/javaworld/jw-04-2003/jw-0425-designpatterns.html?page=6 Describes a SingletonRegistry whose purpose is to store Singletons! public static Singleton getInstance() { return (Singleton) SingletonRegistry.REGISTRY .getInstance(classname); }
38. Case Study: Dependencies public class Searcher { //Singleton Setup code Here public Collection FindCustomers(String criteria) { String conStr = GetConnectionFromRegistry(); OracleConnection conn = new OracleConnection(conStr); //Query database using criteria return (Collection of customers); } } 05/27/10
39. Case Study: Dependencies To search the database, the client code would need to do the following: Searcher.getInstance().FindCustomers(“some criteria”) What happens if we need to change the database to SQL Server? Or change how we get the connection string?
40. Case Study: Dependencies The Singleton is tightly coupled to Oracle. If the database changed in the future, this object would need to be changed. It is also tightly coupled in how it retrieves the connection string. The Singleton hides object dependencies (Oracle and registry). Anyone using the Singleton would need to inspect the internals to find out what is really going on. Possibly memory leak since the Singleton may hold onto the resource for an infinite amount of time. 05/27/10
41. Unit Testing There are many problems with unit testing a Singleton. Problem : If you are running multiple unit tests that accesses the same Singleton, the Singleton will retain state between unit tests. This may lead to undesired results! Solution : Use Reflection to get access to the private static instance variable. Then set it to null. This should be done at the end of each unit test. private static Singleton uniqueInstance; 05/27/10
42. Unit Testing Other problems You want to unit test a method of a Singleton, but the method refers to other external resources. It is hard to inject a mock in this case. You are unit testing a method that does a lot of business logic. One of the method calls is a Singleton that accesses an external resource. How can you replace the Singleton with a mock call? 05/27/10
43. Scott Densmore “Why Singletons are Evil” “… the dependencies in your design are hidden inside the code, and not visible by examining the interfaces of your classes and methods. You have to inspect the code to understand exactly what other objects your class uses. “ Singletons allow you to limit creation of your objects... you are mixing two different responsibilities into the same class.” “ Singletons promote tight coupling between classes.” “ Singletons carry state with them that last as long as the program lasts…Persistent state is the enemy of unit testing.” Source: http://blogs.msdn.com/scottdensmore/archive/2004/05/25/140827.aspx 05/27/10
44. Jeremy D. Miller “Chill out on the Singleton…” “ Using a stateful singleton opens yourself up to all kinds of threading issues. When you screw up threading safety you can create really wacky bugs that are devilishly hard to reproduce. My best advice is to not use caching via static members until you absolutely have to for performance or resource limitation reasons.” Source: http://codebetter.com/blogs/jeremy.miller/archive/2005/08/04/130302.aspx 05/27/10
45. “ How to Decontaminate a Singleton” “ Define a Spring bean for each Singleton you use. For new DI-like implementations use the Spring bean as a wrapper that allows to access the functionality of the Singleton.” http://blog.rainer.eschen.name/2006/12/15/how-to-decontaminate-a-singleton/ 05/27/10
46. Comments from Others “ Sub-classing or creating mocks for Singletons is impossible (unless it implements an interface for its type)” “ It really should only be used in cases of classes for Constants for example.” “ Access to a singleton in an application must be serialized, which complicates multi-threading issues in applications hence introducing possible issues of thread locking.” 05/27/10
47. Comments from Others “ I had cases where I wanted to create a subclass, and the singleton kept referring to the superclass.” “ ..writing a good unit test was impossible because the class invoked a singleton, and there was no way to inject a fake.” “ Unit testing a singleton is not so much a problem as unit testing the other classes that use a singleton. They are bound so tightly that there is often no way to inject a fake (or mock) version of the singleton class. In some cases you can live with that, but in other cases, such as when the singleton accesses an external resource like a database, it's intolerable for a unit test.” 05/27/10
48. Other Useful Articles Singleton Explained http://c2.com/cgi/wiki?SingletonPattern http://www.oodesign.com/singleton-pattern.html Unit Testing http://imistaken.blogspot.com/2009/11/unit-testing-singletons.html http://weblogs.asp.net/okloeten/archive/2004/08/19/217182.aspx
49. SUMMARY Pattern Name – Singleton Problem – Ensures one instance of an object and global access to it. Solution Hide the constructor Use static method to return one instance of the object Consequences Lazy Instantiation Threading Inheritance issues Hides dependencies Difficult unit testing 05/27/10