Design Pattern Interview question and answers
What is a software design pattern?
A design pattern is a solution to a general software problem within a particular context.
Context:
A recurring set of situations where the pattern applies.
Problem:
A System of forces (goals and constraints) that occur repeatedly in this context.
Solution:
A description of communicating objects and classes (collaboration) that can be applied to resolve those forces.
Why is the study of patterns important?
As initial software designs are implemented and deployed, programmers often discover improvements which make the designs more adaptable to change. Design patterns capture solutions that have evolved over time as developers strive for greater flexibility in their software, and they document the solutions in a way which facilitates their reuse in other, possibly unrelated systems. Design patterns allow us to reuse the knowledge of experienced software designers.
3)How do I document a design pattern?
A pattern description must address the following major points:
Pattern Name and Classification
A short, meaningful name for the pattern, usually only one or two words. Names provide a vocabulary for patterns, and they have implied semantics – choose names carefully. Following the GoF book, we can also group patterns into higher level classifications such as creational, structural, and behavioral patterns.
Problem:
A general description of the problem context and the goals and constraints that occur repeatedly in that context. A concrete motivational scenario can be used to help describe the problem. The problem description should provide guidance to assist others in recognizing situations where the pattern can be applied.
Solution:
The classes and/or objects that participate in the design pattern, their structure (e.g., in terms of a UML class diagram), their responsibilities, and their collaborations. The solution provides an abstract description that can be applied in many different situations. Sample Code in an object-oriented language can be used to illustrate a concrete realization of the pattern.
Consequences:
A discussion of the results and tradeoffs of applying the pattern. Variations and language-dependent alternatives should also be addressed.
Known Uses:
Examples of the pattern in real systems. Look for applications of the pattern in language libraries and frameworks, published system descriptions, text books, etc. Not every good solution represents a pattern. A general rule of thumb is that a candidate pattern (also called a “proto-pattern”) should be discovered in a minimum of three existing systems before it can rightfully be called a pattern.
The following quote by Robert Martin highlights the importance of providing pattern descriptions: “The revolutionary concept of the GoF book is not the fact that there are patterns; it is the way in which those patterns are documented. ... Prior to the GoF book, the only good way to learn patterns was to discover them in design documentation, or (more probably) code.”
4)Where can I learn more about design patterns?
The best place to start is the seminal work by Erich Gamma, Richard Helm, Ralph Johnson, and John Vlissides (collectively known as the “Gang of Four” or simply “GoF”) entitled
Warning: This book is not light reading. From the Preface: “Don't worry if you don't understand this book completely on the first reading. We didn't understand it all on the first writing.”
It is, however, a book which wears well over time, and it is definitely worth the effort required to work through it.
What is an example of a design pattern?
Following the lead of the “Gang of Four” (GoF), design pattern descriptions usually contain multiple sections including
* Intent
* Motivation
* Applicability
* Structure
* Participants
* Collaborations
* Consequences
* Implementation
* Sample Code
* Known Uses
* Related Patterns
A complete discussion of even a small pattern is beyond the scope of a simple FAQ entry, but it is possible to get the idea by examining an abbreviated discussion of one of the simplest and most easily understood patterns. Consider the Singleton pattern, whose intent reads as follows:
Intent: Ensure that a class has one instance, and provide a global point of access to it.
Almost every programmer has encountered this problem and formulated an approach for solving it in a general way – some solutions are better than others. The solution offered by the GoF would look something like the following when coded in java.
Showing posts with label design patterns. Show all posts
Showing posts with label design patterns. Show all posts
Design Pattern --Factory Patterns
A Factory Patterns creates an Interface for creating object and lets subclass do the instantiation. A Factory Pattern lets a class to defer instantiation to the subclasses. Simply saying it abstracts the instance creation.
Overview:
It lets the developer create an interface and retains which class needs to be instantiated. The Factory pattern comes under the category of Creational Patterns.
Generally when we create a class, we will provide constructors to the users of the class so they can create instances for the classes. But on some situations we need or should not give them the ability to create instances with the available classes. On such situations we can create Factory Pattern. That is rather than calling the constructors for creating objects, you are calling the Factory to create objects.
Its primary purpose is to create objects like a real work Factory.
Logical Model:
The prime actors of the Factory Pattern are:
· Client
· Factory
· Product
Product:
A product can be anything you produce in the factory. In programmatic angle it will the actual object which needs to be created.
Factory:
A Factory is the one who creates object of the product.
Client:
A client instead of directly creating objects of the product uses the Factory to create objects for it. The client is not aware about how the objects are created.
Factory Pattern in .net Framework:
Some of the areas where Factory Pattern is used are given below,
IClassFactory is an interface used to create instances of COM classes.
· System.Web.IHttpHandlerFactory class
· System.Convert
Example in C#:
In this example we are going to create we use Abstract classes instead of Interfaces as Abstract classes has the benefits like versioning, etc., over Interfaces.
using System;
using System.Collections.Generic;
using System.Text;
namespace FactoryDemo
{
abstract class Car
{
public abstract int Speed { get; }
}
abstract class CarFactory
{
public abstract Car ShowCar();
}
//Concrete is nothing but the implementaion for the absract classes
class ConcreteCar : Car
{
int _speed = 300;
public override int Speed
{
get { return _speed; }
}
}
class ConcreteCarFactory : CarFactory
{
public override Car ShowCar()
{
return new ConcreteCar();
}
}
class CarCompany
{
public void ProduceCar(CarFactory objfac)
{
Car mycar = objfac.ShowCar();
Console.Write("Car Produced with speed: " + mycar.Speed);
Console.Read();
}
}
class Program
{
static void Main(string[] args)
{
CarFactory mycarfactory = new ConcreteCarFactory();
new CarCompany().ProduceCar(mycarfactory);
}
}
}
Here the abstract classes Car and CarFactory provides the interface and the classes ConcreteCar and ConcreteCarFactory provides the implementation for the abstract classes. The CarCompany class uses all these to make the factory work.
In the simillar way you can create as many of Cars with different model like RollsRoye, Honda and there by creating classes for them by inheriting the classes Car and CarFactory.
But remember that the CarCompany class is abstracted from other classes.
Overview:
It lets the developer create an interface and retains which class needs to be instantiated. The Factory pattern comes under the category of Creational Patterns.
Generally when we create a class, we will provide constructors to the users of the class so they can create instances for the classes. But on some situations we need or should not give them the ability to create instances with the available classes. On such situations we can create Factory Pattern. That is rather than calling the constructors for creating objects, you are calling the Factory to create objects.
Its primary purpose is to create objects like a real work Factory.
Logical Model:
The prime actors of the Factory Pattern are:
· Client
· Factory
· Product
Product:
A product can be anything you produce in the factory. In programmatic angle it will the actual object which needs to be created.
Factory:
A Factory is the one who creates object of the product.
Client:
A client instead of directly creating objects of the product uses the Factory to create objects for it. The client is not aware about how the objects are created.
Factory Pattern in .net Framework:
Some of the areas where Factory Pattern is used are given below,
IClassFactory is an interface used to create instances of COM classes.
· System.Web.IHttpHandlerFactory class
· System.Convert
Example in C#:
In this example we are going to create we use Abstract classes instead of Interfaces as Abstract classes has the benefits like versioning, etc., over Interfaces.
using System;
using System.Collections.Generic;
using System.Text;
namespace FactoryDemo
{
abstract class Car
{
public abstract int Speed { get; }
}
abstract class CarFactory
{
public abstract Car ShowCar();
}
//Concrete is nothing but the implementaion for the absract classes
class ConcreteCar : Car
{
int _speed = 300;
public override int Speed
{
get { return _speed; }
}
}
class ConcreteCarFactory : CarFactory
{
public override Car ShowCar()
{
return new ConcreteCar();
}
}
class CarCompany
{
public void ProduceCar(CarFactory objfac)
{
Car mycar = objfac.ShowCar();
Console.Write("Car Produced with speed: " + mycar.Speed);
Console.Read();
}
}
class Program
{
static void Main(string[] args)
{
CarFactory mycarfactory = new ConcreteCarFactory();
new CarCompany().ProduceCar(mycarfactory);
}
}
}
Here the abstract classes Car and CarFactory provides the interface and the classes ConcreteCar and ConcreteCarFactory provides the implementation for the abstract classes. The CarCompany class uses all these to make the factory work.
In the simillar way you can create as many of Cars with different model like RollsRoye, Honda and there by creating classes for them by inheriting the classes Car and CarFactory.
But remember that the CarCompany class is abstracted from other classes.
Design Patterns Interview questions basic
Design Patterns Interview questions basic
Design Patterns are best proven techniques for a common design problem.
It is only a design technique and not code. Though code is available for almost all design patterns in all popular languages, design patterns mean the design technique alone.
Each design pattern explains a repeated problem, gives standard solution to the problem.
Types of Patterns:Design Patterns are generally classified into three categories, they are:
1. Creational
2. Structural
3. Behavioral
1. CreationalThey deal with object creation. They provide you the best way to create objects based on the current situation.
Example:
Singleton, Factory method, Abstract factory, Builder
2. StructuralThey deal with relationship between entities. They provide you the best way to relate entities on various scenarios.
Example:
Adapter, Aggregate, Bridge
3. BehavioralThey deal with communication between objects. They provide you the best way to communicate between objects.
Example:
Chain of responsibility, Command, Interpreter
Further Classification: Though the above three are the major classification, one more category also exists which may be considered as a sub part of the above. It is:
ConcurrencyThey deal with multi-threaded programs. They provide solutions for multi-thread design problems.
Example:
Balking, Double checked locking, guarded suspension
OOP Techniques and Design Patterns:Before going into design patterns, we need to know some of the OOP (Object Oriented Programming) features, which will in turn lead to a better understanding of Design patterns.
Let us now see the OOPs features one by one,
Class: It defines characteristics of a thing and its behavior. It is blueprint from based on which objects are created.
Example: Employee (which will have all the details about the employee like name, id, salary, etc and the methods which describes his behavior like calcSalary(),displaydetails(),etc.
Object: Is an instance of a class. It will be exactly the same as a class but can be assigned values and used whereas a class can’t be used without creating objects.
Inheritance:
A feature in which the base class’s characteristics and behavior are derived to the child class also.
Types:
Single
Multiple
Single:
A class inherits from a single class.
Multiple:
A class inherits from more than 1 class.
Abstraction: “Abstraction is simplifying complex reality by modeling classes appropriate to the problem, and working at the most appropriate level of inheritance for a given aspect of the problem.” Is what the Wikipedia says.
Encapsulation: It is a feature which hides data and functions from others classes.
Polymorphism: A feature using which more than one definition is given to a single name. It can either be function polymorphism or operator overloading.
Association: Association defines a relationship between classes of objects which allows one object to cause another to perform an action on its behalf.
Composition:
Composition is a way to combine simple objects or data types into more complex ones.
Aggregation: Aggregation is a form of composition where one looks at the system as a whole rather than as parts.
Design Patterns are best proven techniques for a common design problem.
It is only a design technique and not code. Though code is available for almost all design patterns in all popular languages, design patterns mean the design technique alone.
Each design pattern explains a repeated problem, gives standard solution to the problem.
Types of Patterns:Design Patterns are generally classified into three categories, they are:
1. Creational
2. Structural
3. Behavioral
1. CreationalThey deal with object creation. They provide you the best way to create objects based on the current situation.
Example:
Singleton, Factory method, Abstract factory, Builder
2. StructuralThey deal with relationship between entities. They provide you the best way to relate entities on various scenarios.
Example:
Adapter, Aggregate, Bridge
3. BehavioralThey deal with communication between objects. They provide you the best way to communicate between objects.
Example:
Chain of responsibility, Command, Interpreter
Further Classification: Though the above three are the major classification, one more category also exists which may be considered as a sub part of the above. It is:
ConcurrencyThey deal with multi-threaded programs. They provide solutions for multi-thread design problems.
Example:
Balking, Double checked locking, guarded suspension
OOP Techniques and Design Patterns:Before going into design patterns, we need to know some of the OOP (Object Oriented Programming) features, which will in turn lead to a better understanding of Design patterns.
Let us now see the OOPs features one by one,
Class: It defines characteristics of a thing and its behavior. It is blueprint from based on which objects are created.
Example: Employee (which will have all the details about the employee like name, id, salary, etc and the methods which describes his behavior like calcSalary(),displaydetails(),etc.
Object: Is an instance of a class. It will be exactly the same as a class but can be assigned values and used whereas a class can’t be used without creating objects.
Inheritance:
A feature in which the base class’s characteristics and behavior are derived to the child class also.
Types:
Single
Multiple
Single:
A class inherits from a single class.
Multiple:
A class inherits from more than 1 class.
Abstraction: “Abstraction is simplifying complex reality by modeling classes appropriate to the problem, and working at the most appropriate level of inheritance for a given aspect of the problem.” Is what the Wikipedia says.
Encapsulation: It is a feature which hides data and functions from others classes.
Polymorphism: A feature using which more than one definition is given to a single name. It can either be function polymorphism or operator overloading.
Association: Association defines a relationship between classes of objects which allows one object to cause another to perform an action on its behalf.
Composition:
Composition is a way to combine simple objects or data types into more complex ones.
Aggregation: Aggregation is a form of composition where one looks at the system as a whole rather than as parts.
Describe some common design patterns
Describe some common design patterns
Creational Patterns
Abstract Factory Creates an instance of several families of classes
Builder Separates object construction from its representation
Factory Method Creates an instance of several derived classes
Prototype A fully initialized instance to be copied or cloned
Singleton A class of which only a single instance can exist
Structural Patterns
Adapter Match interfaces of different classes
Bridge Separates an object’s interface from its implementation
Composite A tree structure of simple and composite objects
Decorator Add responsibilities to objects dynamically
Façade A single class that represents an entire subsystem
Flyweight A fine-grained instance used for efficient sharing
Proxy An object representing another object
Behavioral Patterns
Chain of Resp. A way of passing a request between a chain of objects
Command Encapsulate a command request as an object
Interpreter A way to include language elements in a program
Iterator Sequentially access the elements of a collection
Mediator Defines simplified communication between classes
Memento Capture and restore an object's internal state
Observer A way of notifying change to a number of classes
State Alter an object's behavior when its state changes
Strategy Encapsulates an algorithm inside a class
Template Method Defer the exact steps of an algorithm to a subclass
Visitor Defines a new operation to a class without change
Creational Patterns
Abstract Factory Creates an instance of several families of classes
Builder Separates object construction from its representation
Factory Method Creates an instance of several derived classes
Prototype A fully initialized instance to be copied or cloned
Singleton A class of which only a single instance can exist
Structural Patterns
Adapter Match interfaces of different classes
Bridge Separates an object’s interface from its implementation
Composite A tree structure of simple and composite objects
Decorator Add responsibilities to objects dynamically
Façade A single class that represents an entire subsystem
Flyweight A fine-grained instance used for efficient sharing
Proxy An object representing another object
Behavioral Patterns
Chain of Resp. A way of passing a request between a chain of objects
Command Encapsulate a command request as an object
Interpreter A way to include language elements in a program
Iterator Sequentially access the elements of a collection
Mediator Defines simplified communication between classes
Memento Capture and restore an object's internal state
Observer A way of notifying change to a number of classes
State Alter an object's behavior when its state changes
Strategy Encapsulates an algorithm inside a class
Template Method Defer the exact steps of an algorithm to a subclass
Visitor Defines a new operation to a class without change
Subscribe to:
Posts (Atom)