0% found this document useful (0 votes)
37 views26 pages

Week 4-1

Uploaded by

jikeb70500
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
37 views26 pages

Week 4-1

Uploaded by

jikeb70500
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 26

CT-365 SOFTWARE ENGINEERING

LECTURE 4

DESIGN PATTERNS – I

HUMA TABASSUM
LECTURER
DEPT. OF COMPUTER SCIENCE & INFORMATION TECHNOLOGY
NED UNIVERSITY OF ENGINEERING & TECHNOLOGY
Design Patterns
• A design pattern is a way of reusing abstract knowledge about a
problem and its solution.

• A pattern is a description of the problem and the essence of its


solution.

• It should be sufficiently abstract to be reused in different settings.

• Pattern descriptions usually make use of object-oriented


characteristics.
2
3
Gang of Four (GoF)

Erich Gamma, Richard Helm, Ralph Johnson, and John Vlissides

4
GoF
• Design Patterns in Computer Science achieved prominence
when Design Pattern: Elements of Reusable Object-Oriented
Software was published in 1994 by authors Erich Gamma, Richard
Helm, Ralph Johnson, and John Vlissides.

• These authors are also known as the Gang of Four (GoF).

• This book contains 23 classic design patterns.

• After this book, many programmers adopted and created their own
design patterns, referring to these classic patterns as bases. 5
6
Singleton Pattern
• Singleton pattern is a type of creational design pattern.
• Creational patterns are the design patterns that deal with the creation
of an object.
• GoF Definition
• Ensure a class only has one instance, and provide a global point of access to it.
• Concept
• A class cannot have multiple instances.
• Once created, the next time onward, you use only the existing instance.
• This approach helps you restrict unnecessary object creations in a centralized
system.
• The approach also promotes easy maintenance.
7
Real-World Example
• Let’s assume that you are a member of a sports team, and your team is
participating in a tournament.
• Your team needs to play against multiple opponents throughout the
tournament.
• Before each of these matches, as per the rules of the game, the captains of
the two sides must do a coin toss.
• If your team does not have a captain, you need to elect someone as a captain.
• Prior to each game and each coin toss, you may not repeat the process of
electing a captain if you already nominated a person as a captain for the team.
• Basically, from every team member’s perspective, there should be only one
captain of the team.
8
Computer-World Example
• In some specific software systems, you may prefer to use only one file
system for the centralized management of resources.
• Also, this pattern can implement a caching mechanism.
• Another example of the singleton pattern is configuration or logging.
• LogManager.getLogManager returns the LogManager, and you
cannot create new ones.
• Likewise you might have one common configuration object which can
be accessed statically.

9
10
Illustration

11
Implementation
package jdp2e.singleton.demo;
final class Captain {
private static Captain captain;
//We make the constructor private to prevent the use of "new"
private Captain() { }
public static synchronized Captain getCaptain() {
// Lazy initialization
if (captain == null) {
captain = new Captain();
System.out.println("New captain is elected for your team.");
}
else {
System.out.print("You already have a captain for your team.");
System.out.println("Send him for the toss.");
}
return captain;
}
}
// We cannot extend Captain class. The constructor is private in this case. 12
//class B extends Captain{}// error

public class SingletonPatternExample {


public static void main(String[] args) {
System.out.println("***Singleton Pattern Demo***\n");
System.out.println("Trying to make a captain for your team:");

//Constructor is private. We cannot use "new" here.


//Captain c3 = new Captain();//error

Captain captain1 = Captain.getCaptain();


System.out.println("Trying to make another captain for your team:");
Captain captain2 = Captain.getCaptain();
if (captain1 == captain2) {
System.out.println("captain1 and captain2 are same instance.");
}
}
} 13
Output
***Singleton Pattern Demo***
Trying to make a captain for your team:
New captain is elected for your team.
Trying to make another captain for your team:
You already have a captain for your team.Send him for the toss.
captain1 and captain2 are same instance.

14
Discussion
• These are the key characteristics in the following implementation.
• The constructor is private to prevent the use of a “new” operator.
• You cannot instantiate the Singleton class(Captain) outside.
• It helps us to refer the only instance that can exist in the system, and at the same time,
you restrict the additional object creation of the Captain class.
• You’ll create an instance of the class, if you did not create any such instance
earlier; otherwise, you’ll simply reuse the existing one.
• The private constructor also ensures that the Captain class cannot be extended.
• So, subclasses cannot misuse the concept.
• To take care of thread safety, the “synchronized” keyword is used.
• So, multiple threads cannot involve in the instantiation process at the same time.
• Each thread is forced to wait its turn to get the method, so thread- safety is ensured.
• But synchronization is a costly operation and once the instance is created, it is an
additional overhead.
• There are alternate methods; each having its own pros and cons. 15
Benefits Downsides
• Provides a single point of access to • Can make code harder to test,
a shared resource or global state, since singletons can introduce
which can simplify code and reduce hidden dependencies that are
the potential for errors caused by difficult to mock or substitute.
multiple instances of the same • Can be a source of contention in
resource. multi-threaded or concurrent
• Ensures that only one instance of a applications, since multiple threads
class exists at any given time, which may attempt to access or modify
can help to conserve memory and the singleton simultaneously.
improve performance. • Can lead to tight coupling between
• Can be used to enforce certain different parts of the application,
constraints, such as limiting the since the singleton instance may be
number of connections to a accessed from multiple classes or
database or preventing concurrent modules.
modification of a shared resource. 16
Adapter Pattern
• Adapter pattern is a type of structural design pattern.
• Structural patterns deal with the class structure such as Inheritance
and Composition.

• GoF Definition
• Convert the interface of a class into another interface that clients expect.
Adapter lets classes work together that could not otherwise because of
incompatible interfaces.

17
Real-World Example
• A very common use of this pattern can be seen in an electrical outlet
adapter/AC power adapter in international travels.
• These adapters act as a middleman when an electronic device (let’s say, a
laptop) that accepts a US power supply can be plugged into a European
power outlet.
• Consider another example.
• Suppose that you need to charge your mobile phone, but you see that the
switchboard is not compatible with your charger.
• In this case, you may need to use an adapter.
• Or, a translator who is translating language for someone can be
considered following this pattern in real life.
18
19
Computer-World Example
• Suppose that you have an application that can be broadly classified into two
parts: user interface (UI or front end) and database (back end).
• Through the user interface, clients can pass a specific type of data or objects.
• Your database is compatible with those objects and can store them
smoothly.
• Over a period of time, you may feel that you need to upgrade your software
to make your clients happy.
• So, you may want to allow new type of objects to pass through the UI.
• But in this case, the first resistance comes from your database because it
cannot store these new types of objects.
• In such a situation, you can use an adapter that takes care of the conversion
of the new objects to a compatible form that your old database can accept.20
Illustration

21
Implementation
package jdp2e.adapter.demo; class CalculatorAdapter {
public double getArea(Triangle triangle) {
class Rectangle { Calculator c = new Calculator();
public double length; Rectangle rect = new Rectangle();
public double width; //Area of Triangle=0.5*base*height
rect.length = triangle.base;
}
rect.width = 0.5 * triangle.height;
class Calculator { return c.getArea(rect);
public double getArea(Rectangle rect) { }
return rect.length * rect.width; }
}
} class AdapterPatternExample {
public static void main(String[] args) {
class Triangle { System.out.println("***Adapter Pattern Demo***\n");
public double base;//base CalculatorAdapter calculatorAdapter = new CalculatorAdapter();
public double height;//height Triangle t = new Triangle(20,10);
public Triangle(int b, int h) { System.out.println("Area of Triangle is " +
calculatorAdapter.getArea(t) + " Square unit");
this.base = b; }
this.height = h; }
}
22
}
Output
***Adapter Pattern Demo***
Area of Triangle is 100.0 Square unit

23
Discussion
• In this example, you can easily calculate the area of a rectangle.
• If you notice the Calculator class and its getArea() method, you understand that you need
to supply a rectangle object in the getArea() method to calculate the area of the
rectangle.
• Now suppose that you want to calculate the area of a triangle, but your constraint is that
you want to get the area of it through the getArea() method of the Calculator class.
• So how can you achieve that?
• To deal with this type of problem, a CalculatorAdapter is made for the Triangle class and
is passed a triangle in its getArea() method.
• In turn, the method treats the triangle like a rectangle and calculates the area from the
getArea() method of the Calculator class.

• This a very simple example of the adapter design pattern.


• But if you want to strictly follow object-oriented design principles, you may want to
modify the implementation because you have learned that instead of using concrete
classes, you should always prefer to use interfaces.
24
Benefits Downsides
• The Adapter pattern can facilitate the • The use of adapters can add additional
integration of different systems or layers of complexity to the codebase,
components by providing a common which can make it harder to understand
interface that both can understand. and maintain.
• It is flexible – you can swap or extend the • Using an adapter can introduce
adapters without affecting the rest of the performance overhead depending on the
system. implementation, as additional processing
• Adapters can be reused with different may be required to translate data between
adaptees, making it easy to use the same different interfaces.
adapter with different systems. • If the adapter is tightly coupled to the
• The Adapter pattern allows the client code adaptee, it can create a dependency that
to remain separate from the adaptee may make it harder to modify the adaptee.
code, which makes it easier to modify; • If errors occur within the adaptee code,
thereby, improving readability and they may be obscured by the adapter,
usability. which can make it harder to diagnose and
• The Adapter pattern can improve code fix problems.
maintainability by reducing the number of
dependencies between components.
25
26

You might also like