This document discusses three design patterns: Adapter, Bridge, and Composite.
The Adapter pattern allows classes with incompatible interfaces to work together by wrapping its interface into a compatible one. The Bridge pattern decouples an abstraction from its implementation, allowing them to vary independently. The Composite pattern allows treating individual objects and compositions of objects uniformly.
The document discusses the Abstract Factory and Builder design patterns. It defines Abstract Factory as providing a higher level of interface than Factory Method by returning one of several factories. Builder is defined as constructing complex objects step-by-step by separating the construction from the representation. Examples are provided for both patterns to illustrate how they can be implemented. Related patterns like Factory Method, Singleton, and Prototype are also discussed in relation to Abstract Factory and Builder.
The document discusses Java collection framework. It defines that an array is a collection of elements stored in continuous memory locations with fixed size. Collections were introduced in Java 1.2 to overcome array limitations. The document describes common collection interfaces like List, Set, Map and their implementation classes like ArrayList, LinkedList, HashSet, TreeSet, HashMap etc. It provides details about various collection classes like their creation, methods and differences.
The document discusses several design patterns including Singleton, Factory Method, Strategy, and others. It provides descriptions of the patterns, examples of how they can be implemented in code, and discusses how some patterns like Singleton can be adapted for multi-threaded applications. It also briefly introduces the Multiton pattern, which is an extension of Singleton that allows multiple instances associated with different keys.
Die SOLID Prinzipien gehören heutzutage zum festen Handwerkszeug eines jeden Clean Code Developers. Java 8 enthält großartige Neuerungen und Sprach-Features, die aus der Sicht der SOLID-Prinzipien beleuchtet werden. Sie werden erfahren, in welchen Bereichen die Sprache uns Entwickler noch besser unterstützt und wie die JDK-Designer ihrerseits die SOLID-Prinzipien berücksichtigt haben.
Gehen Sie mit mir auf einen Streifzug durch die Java 8 Welt und lernen Sie die neuen Sprachfeatures SOLIDe kennen.
This document provides an overview of classes in Java. It discusses key concepts like class templates, objects, fields, methods, access modifiers, constructors, static members, and class design best practices. Specifically, it defines a class as a template for objects that encapsulates data and functions, and notes that objects are instances of classes. It also explains how to declare fields and methods, the different access levels for class members, and how to define constructors including overloaded and parameterized constructors.
The document discusses defining programmer-defined classes in Java. It provides an example of defining a Bicycle class with data members and methods, and using it to track bicycle ownership. It then expands on this example by defining an Account class and using both classes in a sample program. The key aspects covered include defining classes, using visibility modifiers, passing objects to methods, and differentiating local variables from data members and parameters.
The document discusses basic JDBC programming concepts including connecting to a database, executing SQL statements using Statement, PreparedStatement, and ResultSet objects, and mapping between Java and SQL data types. Key methods for connecting to a database, executing queries and updates, retrieving results, and setting parameters in PreparedStatements are described.
The document discusses the Abstract Factory and Builder design patterns. It defines Abstract Factory as providing a higher level of interface than Factory Method by returning one of several factories. Builder is defined as constructing complex objects step-by-step by separating the construction from the representation. Examples are provided for both patterns to illustrate how they can be implemented. Related patterns like Factory Method, Singleton, and Prototype are also discussed in relation to Abstract Factory and Builder.
The document discusses Java collection framework. It defines that an array is a collection of elements stored in continuous memory locations with fixed size. Collections were introduced in Java 1.2 to overcome array limitations. The document describes common collection interfaces like List, Set, Map and their implementation classes like ArrayList, LinkedList, HashSet, TreeSet, HashMap etc. It provides details about various collection classes like their creation, methods and differences.
The document discusses several design patterns including Singleton, Factory Method, Strategy, and others. It provides descriptions of the patterns, examples of how they can be implemented in code, and discusses how some patterns like Singleton can be adapted for multi-threaded applications. It also briefly introduces the Multiton pattern, which is an extension of Singleton that allows multiple instances associated with different keys.
Die SOLID Prinzipien gehören heutzutage zum festen Handwerkszeug eines jeden Clean Code Developers. Java 8 enthält großartige Neuerungen und Sprach-Features, die aus der Sicht der SOLID-Prinzipien beleuchtet werden. Sie werden erfahren, in welchen Bereichen die Sprache uns Entwickler noch besser unterstützt und wie die JDK-Designer ihrerseits die SOLID-Prinzipien berücksichtigt haben.
Gehen Sie mit mir auf einen Streifzug durch die Java 8 Welt und lernen Sie die neuen Sprachfeatures SOLIDe kennen.
This document provides an overview of classes in Java. It discusses key concepts like class templates, objects, fields, methods, access modifiers, constructors, static members, and class design best practices. Specifically, it defines a class as a template for objects that encapsulates data and functions, and notes that objects are instances of classes. It also explains how to declare fields and methods, the different access levels for class members, and how to define constructors including overloaded and parameterized constructors.
The document discusses defining programmer-defined classes in Java. It provides an example of defining a Bicycle class with data members and methods, and using it to track bicycle ownership. It then expands on this example by defining an Account class and using both classes in a sample program. The key aspects covered include defining classes, using visibility modifiers, passing objects to methods, and differentiating local variables from data members and parameters.
The document discusses basic JDBC programming concepts including connecting to a database, executing SQL statements using Statement, PreparedStatement, and ResultSet objects, and mapping between Java and SQL data types. Key methods for connecting to a database, executing queries and updates, retrieving results, and setting parameters in PreparedStatements are described.
The document discusses design patterns in Java, including the Factory, Abstract Factory, Singleton, and Prototype patterns. It provides code examples to illustrate each pattern. The Factory pattern section shows how to create objects from subclasses without specifying the exact class. The Abstract Factory pattern section demonstrates creating families of related objects without specifying their concrete classes. The Singleton pattern section covers ensuring only one instance of a class is created. And the Prototype pattern section shows copying or cloning existing objects to create new ones instead of using expensive constructors.
An introduction to structural design patterns in object orientation. Suitable for intermediate to advanced computing students and those studying software engineering.
This document discusses Java packages and access control. It defines packages as namespaces that group related classes, and describes how to declare packages and import other packages. It then covers the four access modifiers in Java (public, protected, no modifier, private) and their effects on class, package, subclass and other package access. Code examples are provided to demonstrate how to define packages and use different access modifiers to control visibility and accessibility of classes, variables and methods in Java.
This document provides an introduction to object-oriented programming (OOP) concepts in PHP, including classes, objects, inheritance, and more. It explains that classes define the structure and behavior of objects, and objects are instances of classes. It demonstrates class and object syntax in PHP using a shape class example. It also covers inheritance, abstract classes, interfaces, visibility, static methods/properties, and determining an object's class. The document provides examples to illustrate each OOP concept discussed.
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.
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 provides an overview of defining custom classes in Java, including how to return objects from methods, use the 'this' keyword, define overloaded methods and constructors, create class and static methods, implement parameter passing, organize classes into packages, and document classes with Javadoc comments. Key concepts like inheritance, polymorphism, and abstraction are not discussed. The chapter aims to describe the basics of defining custom classes in Java.
A class definition consists of two parts: header and body. The class header specifies the class name and its base classes. (The latter relates to derived classes and is discussed in Chapter 8.) The class body defines the class members. Two types of members are supported:
Data members have the syntax of variable definitions and specify the representation of class objects.
Member functions have the syntax of function prototypes and specify the class operations, also called the class interface.
Class members fall under one of three different access permission categories:
Public members are accessible by all class users.
Private members are only accessible by the class members.
Protected members are only accessible by the class members and the members of a derived class.
The data type defined by a class is used in exactly the same way as a built-in type.
Interfaces define methods that classes can implement. Classes implementing interfaces must define all interface methods. Interfaces can extend other interfaces, requiring implementing classes to define inherited methods as well. Interface variables are implicitly public, static, and final. A class can implement multiple interfaces and override methods with the same name across interfaces. Partial interface implementation requires the class to be abstract.
The document discusses Java packages and classes. It describes common Java API packages like java.lang, java.util, java.io, java.awt, and java.net and what types of classes they contain. It also provides examples of using packages like Vector, Random, Date, and Calendar classes and their key methods. The Calendar class allows interpreting dates and times, defining constants used for components like MONTH, DATE, HOUR, etc.
This document discusses defining custom classes in Java. It covers topics like returning objects from methods, using the "this" keyword, overloaded methods and constructors, class methods and variables, and organizing classes into packages. Key points include how objects are passed by value to method parameters rather than by reference, and how to document classes using Javadoc comments.
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 strategies for fixing class and package tangling issues. For class tangling, potential solutions include depending on interfaces instead of concrete classes to remove cycles, moving methods that refer to derived classes to a factory class, and removing unnecessary references between classes. For package tangling, solutions involve separating interface and implementation packages, moving misplaced classes to more suitable packages, and splitting packages that contain unrelated classes.
The document discusses key concepts of object-oriented programming (OOP) including objects, classes, constructors, encapsulation, inheritance, and polymorphism. It provides examples to illustrate each concept. Objects contain data (states) and behaviors (methods). A class acts as a blueprint to create objects. Constructors initialize objects. Encapsulation hides implementation details and controls access via getters and setters. Inheritance allows classes to acquire properties and behaviors of other classes. Polymorphism allows the same method to process objects differently based on their data type.
This document provides an overview of key object-oriented programming concepts including classes and objects, inheritance, encapsulation, polymorphism, interfaces, abstract classes, and design patterns. It discusses class construction and object instantiation. Inheritance is described as both exposing implementation details and potentially breaking encapsulation. Composition is presented as an alternative to inheritance. The document also covers method overriding, overloading, and duck typing as forms of polymorphism. Finally, it briefly introduces common design principles like SOLID and patterns like delegation.
Object oriented programming concepts such as abstraction, encapsulation, inheritance and polymorphism are supported in .NET languages like C# and Visual Basic. Encapsulation groups related properties and methods into a single object. Inheritance allows new classes to be created from an existing class. Polymorphism allows multiple classes to be used interchangeably even if they implement properties or methods differently.
The document discusses different creational design patterns, including the Abstract Factory pattern and Factory Method pattern. The Abstract Factory pattern provides an interface for creating families of related objects without specifying their concrete classes. It allows a system to be independent of how its objects are created. The Factory Method pattern defines an interface for creating an object but lets subclasses decide which class to instantiate. It decouples class creation from use through delegation to subclasses.
The document provides definitions and explanations of various object-oriented programming concepts in Delphi such as classes, objects, visibility of class members, inheritance, abstract classes, interfaces, constructors, virtual functions, polymorphism, late binding, encapsulation, properties, exceptions handling, and runtime type information (RTTI). It discusses these concepts through questions and answers. Key points covered include the relationship between classes and objects, differences between visibility levels of class members, how inheritance allows the creation of subclasses, rules around abstract classes and methods, limitations of interfaces, how to define and overload constructors and functions, use of virtual functions and polymorphism, and how RTTI is used.
All 23 classical GOF Design Patterns with illustrations that try to catch some essence of them.
Used in a presentation for Eindhoven Developers, March 17, 2015 http://www.meetup.com/Eindhoven-Developers-Meetup/events/220477660/
introduction, The Resolution of Property Names on Objects.
Closure
A "closure" is an expression (typically a function) that can have
free variables together with an environment that binds those
variables (that "closes" the expression)
The document outlines the course units for an Advanced Java Programming course. Unit 1 covers classes, interfaces, inheritance and encapsulation. Unit 2 discusses methods, method overloading, overriding and recursion. Unit 3 focuses on exceptions, threads and immutability. Unit 4 covers dynamic language support and APIs. Unit 5 is about Java annotation processors and agents.
The document discusses design patterns in Java, including the Factory, Abstract Factory, Singleton, and Prototype patterns. It provides code examples to illustrate each pattern. The Factory pattern section shows how to create objects from subclasses without specifying the exact class. The Abstract Factory pattern section demonstrates creating families of related objects without specifying their concrete classes. The Singleton pattern section covers ensuring only one instance of a class is created. And the Prototype pattern section shows copying or cloning existing objects to create new ones instead of using expensive constructors.
An introduction to structural design patterns in object orientation. Suitable for intermediate to advanced computing students and those studying software engineering.
This document discusses Java packages and access control. It defines packages as namespaces that group related classes, and describes how to declare packages and import other packages. It then covers the four access modifiers in Java (public, protected, no modifier, private) and their effects on class, package, subclass and other package access. Code examples are provided to demonstrate how to define packages and use different access modifiers to control visibility and accessibility of classes, variables and methods in Java.
This document provides an introduction to object-oriented programming (OOP) concepts in PHP, including classes, objects, inheritance, and more. It explains that classes define the structure and behavior of objects, and objects are instances of classes. It demonstrates class and object syntax in PHP using a shape class example. It also covers inheritance, abstract classes, interfaces, visibility, static methods/properties, and determining an object's class. The document provides examples to illustrate each OOP concept discussed.
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.
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 provides an overview of defining custom classes in Java, including how to return objects from methods, use the 'this' keyword, define overloaded methods and constructors, create class and static methods, implement parameter passing, organize classes into packages, and document classes with Javadoc comments. Key concepts like inheritance, polymorphism, and abstraction are not discussed. The chapter aims to describe the basics of defining custom classes in Java.
A class definition consists of two parts: header and body. The class header specifies the class name and its base classes. (The latter relates to derived classes and is discussed in Chapter 8.) The class body defines the class members. Two types of members are supported:
Data members have the syntax of variable definitions and specify the representation of class objects.
Member functions have the syntax of function prototypes and specify the class operations, also called the class interface.
Class members fall under one of three different access permission categories:
Public members are accessible by all class users.
Private members are only accessible by the class members.
Protected members are only accessible by the class members and the members of a derived class.
The data type defined by a class is used in exactly the same way as a built-in type.
Interfaces define methods that classes can implement. Classes implementing interfaces must define all interface methods. Interfaces can extend other interfaces, requiring implementing classes to define inherited methods as well. Interface variables are implicitly public, static, and final. A class can implement multiple interfaces and override methods with the same name across interfaces. Partial interface implementation requires the class to be abstract.
The document discusses Java packages and classes. It describes common Java API packages like java.lang, java.util, java.io, java.awt, and java.net and what types of classes they contain. It also provides examples of using packages like Vector, Random, Date, and Calendar classes and their key methods. The Calendar class allows interpreting dates and times, defining constants used for components like MONTH, DATE, HOUR, etc.
This document discusses defining custom classes in Java. It covers topics like returning objects from methods, using the "this" keyword, overloaded methods and constructors, class methods and variables, and organizing classes into packages. Key points include how objects are passed by value to method parameters rather than by reference, and how to document classes using Javadoc comments.
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 strategies for fixing class and package tangling issues. For class tangling, potential solutions include depending on interfaces instead of concrete classes to remove cycles, moving methods that refer to derived classes to a factory class, and removing unnecessary references between classes. For package tangling, solutions involve separating interface and implementation packages, moving misplaced classes to more suitable packages, and splitting packages that contain unrelated classes.
The document discusses key concepts of object-oriented programming (OOP) including objects, classes, constructors, encapsulation, inheritance, and polymorphism. It provides examples to illustrate each concept. Objects contain data (states) and behaviors (methods). A class acts as a blueprint to create objects. Constructors initialize objects. Encapsulation hides implementation details and controls access via getters and setters. Inheritance allows classes to acquire properties and behaviors of other classes. Polymorphism allows the same method to process objects differently based on their data type.
This document provides an overview of key object-oriented programming concepts including classes and objects, inheritance, encapsulation, polymorphism, interfaces, abstract classes, and design patterns. It discusses class construction and object instantiation. Inheritance is described as both exposing implementation details and potentially breaking encapsulation. Composition is presented as an alternative to inheritance. The document also covers method overriding, overloading, and duck typing as forms of polymorphism. Finally, it briefly introduces common design principles like SOLID and patterns like delegation.
Object oriented programming concepts such as abstraction, encapsulation, inheritance and polymorphism are supported in .NET languages like C# and Visual Basic. Encapsulation groups related properties and methods into a single object. Inheritance allows new classes to be created from an existing class. Polymorphism allows multiple classes to be used interchangeably even if they implement properties or methods differently.
The document discusses different creational design patterns, including the Abstract Factory pattern and Factory Method pattern. The Abstract Factory pattern provides an interface for creating families of related objects without specifying their concrete classes. It allows a system to be independent of how its objects are created. The Factory Method pattern defines an interface for creating an object but lets subclasses decide which class to instantiate. It decouples class creation from use through delegation to subclasses.
The document provides definitions and explanations of various object-oriented programming concepts in Delphi such as classes, objects, visibility of class members, inheritance, abstract classes, interfaces, constructors, virtual functions, polymorphism, late binding, encapsulation, properties, exceptions handling, and runtime type information (RTTI). It discusses these concepts through questions and answers. Key points covered include the relationship between classes and objects, differences between visibility levels of class members, how inheritance allows the creation of subclasses, rules around abstract classes and methods, limitations of interfaces, how to define and overload constructors and functions, use of virtual functions and polymorphism, and how RTTI is used.
All 23 classical GOF Design Patterns with illustrations that try to catch some essence of them.
Used in a presentation for Eindhoven Developers, March 17, 2015 http://www.meetup.com/Eindhoven-Developers-Meetup/events/220477660/
introduction, The Resolution of Property Names on Objects.
Closure
A "closure" is an expression (typically a function) that can have
free variables together with an environment that binds those
variables (that "closes" the expression)
The document outlines the course units for an Advanced Java Programming course. Unit 1 covers classes, interfaces, inheritance and encapsulation. Unit 2 discusses methods, method overloading, overriding and recursion. Unit 3 focuses on exceptions, threads and immutability. Unit 4 covers dynamic language support and APIs. Unit 5 is about Java annotation processors and agents.
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.
An interface in Java is a blueprint of a class that defines static constants and abstract methods. Interfaces are used to achieve abstraction and multiple inheritance in Java. An interface cannot have method bodies and can only contain abstract methods and variables that are public, static, and final by default. Classes implement interfaces to inherit their methods. Since Java 8, interfaces can also contain default and static methods.
Interfaces in Java allow classes to define common behaviors without inheritance. An interface defines abstract methods and constants but provides no implementation. A class implements an interface by providing method bodies for the abstract methods. Interfaces allow for multiple inheritance of behaviors. Default methods were added in Java 8 to allow interfaces to define method implementations for existing classes to optionally use.
Abstract classes allow for defining a generalized superclass that leaves implementation details to subclasses. An abstract class can define methods that subclasses must implement. Abstract classes cannot be instantiated and exist solely to be extended. Interfaces define behaviors and properties but leave implementation to classes that implement the interface. Abstract classes can contain both abstract and concrete methods while interfaces can only contain abstract methods. Both allow for achieving abstraction and multiple inheritance in Java.
The Collection API provides classes and interfaces that support operations on collections of objects, such as HashSet, HashMap, ArrayList, and LinkedList. It replaces vectors, arrays, and hashtables. Iterator is an interface used to iterate through elements of a Collection. The differences between an abstract class and interface are that interfaces provide multiple inheritance while abstract classes do not, and interfaces only define public methods without implementation.
The document discusses key concepts of object-oriented programming including objects, classes, inheritance, polymorphism, encapsulation, and abstraction. It provides examples of constructors, method overloading and overriding, interfaces, and packages in Java.
The document discusses object-oriented programming (OOP) principles including the single responsibility principle (SRP), open/closed principle (OCP), Liskov substitution principle (LSP), interface segregation principle (ISP), and dependency inversion principle (DIP). It provides examples of applying each principle and defines them as: SRP - a class should have one reason to change; OCP - entities should be open for extension but closed for modification; LSP - derived classes must be substitutable for their base classes; ISP - clients shouldn't implement unused interfaces; DIP - high-level modules shouldn't depend on low-level modules but abstract interfaces. The document also reviews OOP concepts in C# code.
The document contains questions and answers related to Java interview questions. It discusses topics like access modifiers, differences between abstract classes and interfaces, garbage collection, constructors vs methods, inheritance, polymorphism, exceptions and more. The questions aim to test the interviewee's understanding of core Java concepts.
The document discusses tools and techniques for making Java development more enjoyable. It recommends using libraries like Mockito, Guice and Guava to simplify testing and dependency injection. It also suggests using builder patterns, writing concise yet descriptive unit tests, and avoiding string-typing in favor of object-oriented types.
1. The document discusses inheritance in Java, including class inheritance which allows extending classes and interface inheritance which allows implementing interfaces. It defines the keywords "extends" for class inheritance and "implements" for interface inheritance.
2. Abstract classes can contain both abstract and non-abstract methods, allowing for some default implementations, while interfaces contain only abstract methods. Interfaces define a contract that implementing classes must follow.
3. Constructors in subclasses implicitly call the parent class constructor before executing the subclass constructor body, following a top-down construction order under inheritance.
This document discusses several design patterns: Factory, Flyweight, Singleton, Observer, Proxy, Decorator. It provides definitions and examples of when to use each pattern. The Factory pattern creates objects without specifying the exact class. Flyweight reduces memory usage by sharing instances. Singleton ensures only one instance exists. Observer notifies dependent objects of state changes. Proxy controls access to another object. Decorator adds new behaviors to an object dynamically.
1. Inheritance in Java allows classes to extend other classes and interfaces to implement other interfaces. This allows code reuse and establishes type constraints.
2. Abstract classes can contain both abstract and non-abstract methods while interfaces contain only abstract methods. Interfaces establish contracts that implementing classes must follow.
3. When constructing objects with inheritance, superclass constructors are called before subclass constructors. Abstract classes and interfaces allow incomplete implementations to be extended.
The document discusses various design principles and patterns in Java including the Singleton, Factory Method, Prototype, and Abstract Factory patterns. It provides examples of when and how to apply each pattern, describing their structures, participants, collaborations and consequences. It also covers design principles such as the open-closed principle, dependency inversion, and interface segregation.
This document summarizes key points from Chapter 4 of Effective Java on classes and interfaces. It discusses 19 items on best practices such as minimizing accessibility of classes and members, using accessor methods over public fields, favoring immutable classes, composition over inheritance, interfaces over abstract classes, and function objects to represent strategies. The document provides examples and explanations for each item.
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.
D.B. Naga Muruga is seeking a career that utilizes his abilities in a growth-oriented environment. He has a B.E. in Mechanical Engineering from Sriram Engineering College with a 7.4 CGPA. He has won awards for best student and best paper at conferences. He has published 15 journals, led project teams, and done internships in marketing, IT, and engineering. His technical skills include manufacturing, design, and digital marketing. He has experience in welding, automotive, and electronics training. References are provided from his college HOD and past employers.
Self-Healing Materials (SHM) today plays a major role in the field of study and research in materials. Alternatively, SHM can be termed as autonomous healing materials, automatics healing materials. These are the type of materials where they can heal themselves, from any impact that causes a dislocation or irregular changes in structure. This paper discusses different types of Self-Healing Materials in-depth and the application of SHM in Concretes. This paper also explains various aspect of SHM like usage of the capsule, mechanical strength, thermal analysis and structures of SHM. This paper further discusses several practical applications of SHM in daily usage as composites, polymers, fiber-reinforced composites, coatings, ceramics, polyurethane foam coatings, and matrices.
This certificate recognizes that D.B.Naga Muruga successfully completed all modules in the Fundamentals of manuscript preparation course on September 22, 2020. The certificate was issued by Suzanne BeDell, Managing Director of Education at Reference & Continuity Books, and Philippe Terheggen, Managing Director of Science, Technology & Medical Journals.
This certificate certifies that D.B.NAGA MURUGA has completed the requirements for AutoCAD 1 (Beginner) through Infratech Civil. The certificate was issued on July 3, 2020 with an identification number of rgjvni8mpj.
This Certificate of Achievement is awarded to D.B.NAGA MURUGA for successfully completing a course on Boiler Types and Opportunities for Energy Efficiency. The certificate has a serial number and date of 05/14/2020 to verify the achievement.
Mr. D.B.NAGA MURUGA completed a web-based training on Basics of Drives - Motors on May 11, 2020, as certified by Sonja Neubert of Siemens Training Services in Germany. The training covered the operating principles, designs, and applications of synchronous motors, asynchronous motors, and reluctance motors, and included a final test.
The confirmation letter confirms that D. B. Naga Muruga successfully completed the Supply Chain Management short course between April 27th and 29th, 2020. The course involved assignments and projects in English and Dr. Irfan Raja, Director of Learning, can provide more details if needed.
The document discusses the benefits of green walls, also known as living walls. Green walls can help control temperature, reduce heat, lower carbon footprints through recycling, provide high sound adsorption, and bring humidity control. They are applicable and practical for both residential and commercial buildings in an affordable way. The document encourages taking responsibility to address global warming through solutions like green walls.
Today, the world has shrunk inside a small smartphone. Still, people prefer moving from one place to another place by transportation to virtual communications. In such a case, people use Public Transports like Buses, Trains, etc. During such a large journey, people who take travel alone will get mental loneliness. But because of mobile phones, those feelings are not existing today. Still, a problem again rises, which is nothing but Depletion of mobile charge during usage. The worst-case scenario here is, Lakhs of mobile phones after a long journey start getting misbehave and hacked. The users won’t have any symptoms that their mobile has been hacked. The reason is when people use their chargers to charge their mobile in a public charging slot, their phones continuously gets hacked. The reason behind this attack is Juice Jacking. A type of cyber-attack conducted by hackers in public charging slots. Usually, a data transporting chip is inserted in the plug point of the charging slot. This chip when gets connected to the charging mobile starts to transfer all the data from the mobile to the hacker without any permission from the user. To avoid this type of attack, a project is designed and fabricated called ANTI JUICE JACKING SMART SOLAR CHARGER. This is a type of Solar operated mobile charging project. This project also helps in providing awareness to the people on Juice Jacking and Solar Energy’s importance.
This document lists and briefly describes 32 different lean manufacturing technologies and tools. It includes common tools like 5S, value stream mapping, standard work, total productive maintenance (TPM), and continuous improvement (Kaizen). The purpose of these tools is to eliminate waste from manufacturing processes, improve flow, reduce lead times and inventory, increase quality, and align goals throughout the organization. Implementing a variety of these lean tools can help companies significantly enhance productivity, customer responsiveness and overall business performance.
Hierarchical Digital Twin of a Naval Power SystemKerry Sado
A hierarchical digital twin of a Naval DC power system has been developed and experimentally verified. Similar to other state-of-the-art digital twins, this technology creates a digital replica of the physical system executed in real-time or faster, which can modify hardware controls. However, its advantage stems from distributing computational efforts by utilizing a hierarchical structure composed of lower-level digital twin blocks and a higher-level system digital twin. Each digital twin block is associated with a physical subsystem of the hardware and communicates with a singular system digital twin, which creates a system-level response. By extracting information from each level of the hierarchy, power system controls of the hardware were reconfigured autonomously. This hierarchical digital twin development offers several advantages over other digital twins, particularly in the field of naval power systems. The hierarchical structure allows for greater computational efficiency and scalability while the ability to autonomously reconfigure hardware controls offers increased flexibility and responsiveness. The hierarchical decomposition and models utilized were well aligned with the physical twin, as indicated by the maximum deviations between the developed digital twin hierarchy and the hardware.
Literature Review Basics and Understanding Reference Management.pptxDr Ramhari Poudyal
Three-day training on academic research focuses on analytical tools at United Technical College, supported by the University Grant Commission, Nepal. 24-26 May 2024
Advanced control scheme of doubly fed induction generator for wind turbine us...IJECEIAES
This paper describes a speed control device for generating electrical energy on an electricity network based on the doubly fed induction generator (DFIG) used for wind power conversion systems. At first, a double-fed induction generator model was constructed. A control law is formulated to govern the flow of energy between the stator of a DFIG and the energy network using three types of controllers: proportional integral (PI), sliding mode controller (SMC) and second order sliding mode controller (SOSMC). Their different results in terms of power reference tracking, reaction to unexpected speed fluctuations, sensitivity to perturbations, and resilience against machine parameter alterations are compared. MATLAB/Simulink was used to conduct the simulations for the preceding study. Multiple simulations have shown very satisfying results, and the investigations demonstrate the efficacy and power-enhancing capabilities of the suggested control system.
DEEP LEARNING FOR SMART GRID INTRUSION DETECTION: A HYBRID CNN-LSTM-BASED MODELgerogepatton
As digital technology becomes more deeply embedded in power systems, protecting the communication
networks of Smart Grids (SG) has emerged as a critical concern. Distributed Network Protocol 3 (DNP3)
represents a multi-tiered application layer protocol extensively utilized in Supervisory Control and Data
Acquisition (SCADA)-based smart grids to facilitate real-time data gathering and control functionalities.
Robust Intrusion Detection Systems (IDS) are necessary for early threat detection and mitigation because
of the interconnection of these networks, which makes them vulnerable to a variety of cyberattacks. To
solve this issue, this paper develops a hybrid Deep Learning (DL) model specifically designed for intrusion
detection in smart grids. The proposed approach is a combination of the Convolutional Neural Network
(CNN) and the Long-Short-Term Memory algorithms (LSTM). We employed a recent intrusion detection
dataset (DNP3), which focuses on unauthorized commands and Denial of Service (DoS) cyberattacks, to
train and test our model. The results of our experiments show that our CNN-LSTM method is much better
at finding smart grid intrusions than other deep learning algorithms used for classification. In addition,
our proposed approach improves accuracy, precision, recall, and F1 score, achieving a high detection
accuracy rate of 99.50%.
Understanding Inductive Bias in Machine LearningSUTEJAS
This presentation explores the concept of inductive bias in machine learning. It explains how algorithms come with built-in assumptions and preferences that guide the learning process. You'll learn about the different types of inductive bias and how they can impact the performance and generalizability of machine learning models.
The presentation also covers the positive and negative aspects of inductive bias, along with strategies for mitigating potential drawbacks. We'll explore examples of how bias manifests in algorithms like neural networks and decision trees.
By understanding inductive bias, you can gain valuable insights into how machine learning models work and make informed decisions when building and deploying them.
New techniques for characterising damage in rock slopes.pdf
Structural pattern 3
1. Structural Pattern - 3
By,
D. B. Naga Muruga,
Dept of Mechanical Engineering,
Sriram Engineering College
2. Adapter Pattern
Define Adapter pattern
Convert the existing interfaces to a new interface to achieve compatibility and reusability of the unrelated classes in
one application. Also known as Wrapper pattern.
The Adapter pattern is used so that two unrelated interfaces can work together. The joining between them is called an
Adapter. This is something like we convert interface of one class into interface expected by the client. We do that using
an Adapter.
Where to use & benefits
Try to match an interface(WindowAdapter, etc.)
Make unrelated classes work together.
Multiple compatibility.
Increase transparency of classes.
Make a pluggable kit.
Delegate objects.
Highly class reusable.
Achieve the goal by inheritance or by composition
Related patterns include
Proxy, which provides the same interface as its subject, whereas an adapter provides a different interface to the object
it adapts.
Decorator, which focuses on adding new functions to an object, whereas an adapter coordinates two different objects.
Bridge, which tries to separate an interface from its implementation and make an object vary independently, whereas
an adapter tries to change and cooperate the interface of an object.
3. Example of Adapter pattern
The famous adapter classes in Java API are
WindowAdapter,ComponentAdapter, ContainerAdapter, FocusAdapter,
KeyAdapter, MouseAdapter and MouseMotionAdapter.
As you know, WindowListner interface has seven methods. Whenever
your class implements such interface, you have to implements all of
the seven methods. WindowAdapter class implements WindowListener
interface and make seven empty implementation. When you class
subclass WindowAdapter class, you may choose the method you want
without restrictions. The following give such an example.
4. public interface Windowlistener {
public void windowClosed(WindowEvent e);
public void windowOpened(WindowEvent e);
public void windowIconified(WindowEvent e);
public void windowDeiconified(WindowEvent e);
public void windowActivated(WindowEvent e);
public void windowDeactivated(WindowEvent e);
public void windowClosing(WindowEvent e);
}
public class WindowAdapter implements WindowListner{
public void windowClosed(WindowEvent e){}
public void windowOpened(WindowEvent e){}
public void windowIconified(WindowEvent e){}
public void windowDeiconified(WindowEvent e){}
public void windowActivated(WindowEvent e){}
public void windowDeactivated(WindowEvent e){}
public void windowClosing(WindowEvent e){}
}
Here is a test program
import javax.swing.*;
import java.awt.event.*;
class Test extends JFrame {
public Test () {
setSize(200,200);
setVisible(true);
addWindowListener(new Closer());
}
public static void main(String[] args) {
new Test();
}
class Closer extends WindowAdapter {
public void windowClosing(WindowEvent e) {
System.exit(0);
}
}
}
To reuse classes and make new class compatible with existing ones. For
example, A clean system is already designed, you want to add more job in,
the Extra interface uses adapter pattern to plug in the existing system.
interface Clean {
public void makeClean();
}
class Office implements Clean{
public void makeClean() {
System.out.println("Clean Office");
}
}
class Workshop implements Clean{
public void makeClean() {
System.out.println("Clean Workshop");
}
}
interface Extra extends Clean{
public void takeCare();
}
class Facility implements Extra{
public void makeClean() {
System.out.println("Clean Facility");
}
public void takeCare() {
System.out.println("Care has been taken");
}
}
In order to reuse Workshop and Office classes,
we create an adapter interface Extra and
add new job takeCare in the system.
class Test {
static void Jobs (Extra job) {
if (job instanceof Clean)
((Clean)job).makeClean();
if ((Extra)job instanceof Extra)
((Extra)job).takeCare();
}
public static void main(String[] args) {
Extra e = new Facility();
Jobs(e);
Clean c1 = new Office();
Clean c2 = new Workshop();
c1.makeClean();
c2.makeClean();
e.makeClean();
}
}
Output :
Clean Facility
Care has been taken
Clean Office
Clean Workshop
Clean Facility
By composition, we can achieve adapter pattern. It is also called wrapper. For
example, a Data class has already been designed and well tested. You want to
adapt such class to your system. You may declare it as a variable and wrapper
or embed it into your class.
//well-tested class
class Data {
public void add(Info){}
public void delete(Info) {}
public void modify(Info){}
//...
}
//Use Data class in your own class
class AdaptData {
Data data;
public void add(Info i) {
data.add(i);
//more job
}
public void delete(Info i) {
data.delete(i);
//more job
}
public void modify(Info i) {
data.modify(i);
//more job
}
//more stuff here
//...
}
5. Bridge Pattern
Define bridge pattern
Decouple an abstraction or interface from its implementation so that the two
can vary independently.
The Bridge Pattern is used to separate out the interface from its
implementation. Doing this gives the flexibility so that both can vary
independently.
Where to use & benefits
Want to separate abstraction and implementation permanently
Share an implementation among multiple objects
Want to improve extensibility
Hide implementation details from clients
6. Related patterns include
Abstract Factory, which can be used to create and configure a
particular bridge.
Adapter, which makes unrelated classes work together, whereas a
bridge makes a clear-cut between abstraction and implementation.
7. Example of bridge pattern
If you have a question database, you may want to
develop a program to display it based on the user
selection. The following is a simple example to show how
to use a Bridge pattern to decouple the relationship
among the objects.
8. import java.util.*;
//abstraction
interface Question {
public void nextQuestion();
public void priorQuestion();
public void newQuestion(String q);
public void deleteQuestion(String q);
public void displayQuestion();
public void displayAllQuestions();
}
//implementation
class QuestionManager {
protected Question questDB; //instantiate it later
public String catalog;
public QuestionManager(String catalog) {
this.catalog = catalog;
}
public void next() {
questDB.nextQuestion();
}
public void prior() {
questDB.priorQuestion();
}
public void newOne(String quest) {
questDB.newQuestion(quest);
}
public void delete(String quest) {
questDB.deleteQuestion(quest);
}
public void display() {
questDB.displayQuestion();
}
public void displayAll() {
System.out.println("Question Catalog: " + catalog);
questDB.displayAllQuestions();
}
}
//further implementation
class QuestionFormat extends QuestionManager {
public QuestionFormat(String catalog){
super(catalog);
}
public void displayAll() {
System.out.println("n~~~~~~~~~~~~~~~~~~~~~~~~");
super.displayAll();
System.out.println("~~~~~~~~~~~~~~~~~~~~~~~~");
}
}
//decoupled implementation
class JavaQuestions implements Question {
private List questions = new ArrayList();
private int current = 0;
public JavaQuestions() {
//load from a database and fill in the container
questions.add("What is Java? ");
questions.add("What is an interface? ");
questions.add("What is cross-platform? ");
questions.add("What is UFT-8? ");
questions.add("What is abstract? ");
questions.add("What is Thread? ");
questions.add("What is multi-threading? ");
}
public void nextQuestion() {
if( current <= questions.size() - 1 )
current++;
}
public void priorQuestion() {
if( current > 0 )
current--;
}
public void newQuestion(String quest) {
questions.add(quest);
}
public void deleteQuestion(String quest) {
questions.remove(quest);
}
public void displayQuestion() {
System.out.println( questions.get(current) );
}
public void displayAllQuestions() {
for (String quest : questions) {
System.out.println(quest);
}
}
}
class TestBridge {
public static void main(String[] args) {
QuestionFormat questions = new QuestionFormat("Java Language");
questions.questDB = new JavaQuestions();//can be hooked up with other
question class
//questions.questDB = new CsharpQuestions();
//questions.questDB = new CplusplusQuestions();
questions.display();
questions.next();
questions.newOne("What is object? ");
questions.newOne("What is reference type?");
questions.displayAll();
}
}
9. //need jdk1.5 to compile
Output :
What is Java?
~~~~~~~~~~~~~~~~~~~~~~~~
Question Catalog: Java Language
What is Java?
What is an interface?
What is cross-platform?
What is UFT-8?
What is abstract?
What is Thread?
What is multi-threading?
What is object?
What is reference type?
~~~~~~~~~~~~~~~~~~~~~~~~
Note that the JavaQuestion class can be launched independently
and work as its own system. Here we just show you how to use
Bridge pattern to decouple the interface from its implementation.
10. Composite pattern
Define Composite pattern
Build a complex object out of elemental objects and itself like a tree structure.
In developing applications, we come across components which are individual
objects and also can be collection of objects. Composite pattern can represent
both the conditions. In this pattern, you can develop tree structures for
representing part-whole hierarchies.
Where to use & benefits
Want to represent a part-whole relationship like tree folder system
Group components to form larger components, which in turn can be grouped to
form still larger components.
11. Related patterns include
Decorator, which is often used with composite pattern and with the same
parent class.
Flyweight, which is used with composite pattern to share components.
Iterator, which is used to traverse the composites.
Visitor, which localizes operations across composite and leaf classes.
12. Example of composite pattern
A component has many elements and itself which has many
elements and itself, etc. A file system is a typical example. Directory
is a composite pattern. When you deal with Directory object, if
isFile() returns true, work on file, if isDirectory() returns true, work on
Directory object.
13. class Directory {
Directory dir;
File[] f;
...
boolean isDirectory() {
return f == null;
}
boolean isFile() {
return f != null;
}
File getFile(int i) {
if (isFile())
return f[i];
return null'
}
Directory getDirectory() {
if (isDirectory())
return dir;
return null;
}
....
}
For example, General Manager may have several employees and some of
employees are Managers which have several employees. To illustrate such issue, we
design a simple Manager class.
class Employee {
String name;
double salary;
Employee(String n, double s){
name = n;
salary = s;
}
String getName() {
return name;
}
double getSalary() {
return salary;
}
public String toString() {
return "Employee " + name;
}
}
class Manager {
Manager mgr;
Employee[] ely;
String dept;
Manager(Manager mgr,Employee[] e, String d ) {
this(e, d);
this.mgr = mgr;
}
Manager(Employee[] e, String d) {
ely = e;
dept =d;
}
String getDept() {
return dept;
}
Manager getManager() {
return mgr;
}
Employee[] getEmployee() {
return ely;
}
public String toString() {
return dept + " manager";
}
}
class Test {
public static void main(String[] args) {
Employee[] e1 = {new Employee("Aaron", 50),
new Employee("Betty", 60)};
Manager m1 = new Manager(e1, "Accounting");
Employee[] e2 = {new Employee("Cathy", 70),
new Employee("Dan", 80),
new Employee("Eliz", 90)};
Manager m2 = new Manager(m1, e2, "Production");
System.out.println(m2);
Employee[] emp = m2.getEmployee();
if (emp != null)
for (int k = 0; k < emp.length; k++)
System.out.println(" "+emp[k]+" Salary: $"+
emp[k].getSalary());
Manager m = m2.getManager();
System.out.println(" " + m);
if (m!= null) {
Employee[] emps = m.getEmployee();
if (emps != null)
for (int k = 0; k < emps.length; k++)
System.out.println(" " + emps[k]+" Salary: $"+
emps[k].getSalary());
}
}
}
Output :
Production manager
Employee Cathy Salary: $70.0
Employee Dan Salary: $80.0
Employee Eliz Salary: $90.0
Accounting manager
Employee Aaron Salary: $50.0
Employee Betty Salary: $60.0
14. Decorator Pattern
Define decorator pattern
Attach additional responsibilities or functions to an object dynamically or statically. Also known
as Wrapper.
The decorator pattern helps to add behavior or responsibilities to an object. This is also called
“Wrapper”. Suppose we have some 6 objects and 2 of them need a special behavior, we can do
this with the help of a decorator.
Where to use & benefits
Provide an alternative to subclassing.
Add new function to an object without affecting other objects.
Make a responsibility easily added and removed dynamically.
More flexibility than static inheritance.
Transparent to the object.
15. Related patterns include
Adapter pattern, which provides a different interface to the object it adapts,
whereas a decorator changes an object's responsibilities,
Proxy pattern, which controls access to the object, whereas a decorator
focuses on adding new functions to an object,
Composite pattern, which aggregates an object, whereas a decorator adds
additional responsibilities to an object, and
Strategy pattern, which changes the guts of an object, whereas a decorator
changes the skin of an object.
Facade pattern, which provides a way of hiding a complex class, whereas a
decorator adds function by wrapping a class.
16. Example of decorator pattern
A JScrollPane object can be used to decorate a JTextArea object or a
JEditorPane object. A window can be decorated with different borders like
BevelBorder, CompoundBorder, EtchedBorder TitledBorder etc. These border
classes working as decorators are provided in Java API.
Decorator pattern can be used in a non-visual fashion. For example,
BufferedInputStream, DataInputStream, and CheckedInputStream are
decorating objects of FilterInputStream class. These decorators are standard
Java API classes.
To illustrate a simple decorator pattern in non-visual manner, we design a
class that prints a number. We create a decorator class that adds a text to
the Number object to indicate that such number is a random number. Of
course we can subclass the Number class to achieve the same goal. But the
decorator pattern provides us an alternative way.
17. import java.util.Random;
class Number {
public void print() {
System.out.println(new Random().nextInt());
}
}
class Decorator {
public Decorator() {
System.out.print("Random number: ");//add a description to the number printed
new Number().print();
}
}
class SubNumber extends Number{
public SubNumber() {
super();
System.out.print("Random number: ");
print();
}
}
class Test {
public static void main(String[] args) {
new Decorator();
new SubNumber();
}
}
Output :
Random number: 145265744
Random number: 145265755
18. Facade Pattern
Define facade pattern
Make a complex system simpler by providing a unified or general interface, which is a higher layer to
these subsystems.
Facade as the name suggests means the face of the building. The people walking past the road can
only see this glass face of the building. They do not know anything about it, the wiring, the pipes and
other complexities. The face hides all the complexities of the building and displays a friendly face.
Where to use & benefits
Want to reduce complexities of a system.
Decouple subsystems , reduce its dependency, and improve portability.
Make an entry point to your subsystems.
Minimize the communication and dependency between subsystems.
Security and performance consideration.
Shield clients from subsystem components.
Simplify generosity to specification.
19. Related patterns include
Abstract Factory, which is often used to create an interface for a
subsystem in an independent way, and can be used as an
alternative way to a facade.
Singleton, which is often used with a facade.
Mediator, which is similar to facade, but a facade doesn't define
new functionality to the subsystem.
20. Example of facade pattern
JDBC design is a good example of Façade pattern. A database design is
complicated. JDBC is used to connect the database and manipulate data
without exposing details to the clients.
Security of a system may be designed with Façade pattern. Clients'
authorization to access information may be classified. General users may be
allowed to access general information; special guests may be allowed to
access more information; administrators and executives may be allowed to
access the most important information. These subsystems may be generalized
by one interface. The identified users may be directed to the related
subsystems.
21. interface General {
public void accessGeneral();
}
interface Special extends General {
public void accessSpecial();
}
interface Private extends General {
public void accessPrivate();
}
class GeneralInfo implements General {
public void accessGeneral() {
//...
}
//...
}
class SpecialInfo implements Special{
public void accessSpecial() {
//...
}
public void accessGeneral() {}
//...
}
class PrivateInfo implements Private, Special {
public void accessPrivate() {
// ...
}
public void accessSpecial() {
//...
}
public void accessGeneral() {
// ...
}
//...
}
class Connection {
//...
if (user is unauthorized) throw new Exception();
if (user is general) return new GeneralInfo();
if (user is special) return new SpecialInfo();
if (user is executive) return new PrivateInfo();
//...
}
The above code example illustrates that the whole system is not
exposed to the clients. It depends on the user classification.
Mr. SudHakar Chavali proposes a better design, similar to the above,
but avoids repeated code. Look at code below.
interface General {
public void accessGeneral();
}
interface Special extends General {
public void accessSpecial();
}
interface Private extends General {
public void accessPrivate();
}
class GeneralInfo implements General {
public void accessGeneral() {
//...
}
//...
}
class SpecialInfo extends GeneralInfo implements Special{
public void accessSpecial() {
//...
}
}
class PrivateInfo extends SpecialInfo implements Private {
public void accessPrivate() {
// ...
}
//...
}
To avoid repeated code, SpecialInfo become subclass of GeneralInfo
and PrivateInfo becomes subclass of SpecialInfo. When a person is
exposed to special information, that person is allowed to access
general information also. When a person is exposed to private
information, that person is allowed to access general information and
special information also.
22. Flyweight Pattern
Define flyweight pattern
Make instances of classes on the fly to improve performance efficiently, like individual
characters or icons on the screen.
The pattern here states about a mechanism by which you can avoid creating a large
number of object instances to represent the entire system.
Where to use & benefits
Need to instantiate a large amount of small and fine-grained classes.
Need icons to represent object.
An object extrinsic state can be shared by classes.
Reduce the number of objects created, decrease memory footprint and increase
performance.
Increase runtime cost associated with transferring, finding, or computing extrinsic data.
23. Related patterns include
Composite, which supports recursive structures, whereas an
flyweight is often applied on it.
Factory Method, which produces specific object upon requirement,
whereas an flyweight uses it to reduce objects.
State, which allows an object to alter its behavior when its internal
state is changed, whereas a flyweight is best implemented on it.
Strategy, which allows an algorithm vary independently to suit its
needs, whereas a flyweight is based on such strategy.
24. Example of flyweight pattern
In order to share an object, we may declare an interface and an
intrinsic state through which flyweights can receive and act on it. If
you want to show a file system with folders to show the directories
or subdirectories, you don't need to load all the files or directories at
one loading time. You may show the upper level folders first. If the
user clicks a folder, then load its subdirectories and files. The shared
trigger is mouse-clicked. The composite pattern may be combined
to define the flyweight system.
25. class Folder {
void draw(..) {}
}
class FolderFactory {
...
if (selected) {
return aFolder;
else
return aFile;
...
}
...
To show how to use flyweight to reduce object creation, we will make a
program to draw 1000 circles with 6 different colors. Before we customize it
to a flyweight design, it is coded as follows:
import java.awt.*;
import java.awt.Color;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.event.*;
class Test extends JFrame{
private static final Color colors[] = { Color.red, Color.blue,
Color.yellow, Color.orange,
Color.black, Color.white };
private static final int WIDTH_ = 400,
HEIGHT = 400,
NUMBER_OF_CIRCLES = 1000;
public Test() {
Container contentPane = getContentPane();
JButton button = new JButton("Draw Circle");
final JPanel panel = new JPanel();
contentPane.add(panel, BorderLayout.CENTER);
contentPane.add(button, BorderLayout.SOUTH);
setSize(WIDTH,HEIGHT);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setVisible(true);
button.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent event) {
Graphics g = panel.getGraphics();
for(int i=0; i < NUMBER_OF_CIRCLES; ++i) {
g.setColor(getRandomColor());
int r = getRandomR();
g.drawOval(getRandomX(), getRandomY(), r, r);
}
}
});
}
private int getRandomX() {
return (int)(Math.random()*WIDTH );
}
private int getRandomY() {
return (int)(Math.random()*HEIGHT);
}
private int getRandomR() {
return (int)(Math.random()*(HEIGHT/10));
}
private Color getRandomColor() {
return colors[(int)(Math.random()*colors.length)];
}
public static void main(String[] args) {
Test test = new Test();
}
}
Copy, paste above code, and run it to see the functionality.
Output :
26.
27. Note that the above program doesn't take advantage of reusability of OOP.
We will customize it and make a Circle object, so the Circle object can be
reused.
class Circle {
private Color color;
public Circle(Color color) {
this.color = color;
}
public void draw(Graphics g, int x, int y, int r) {
g.setColor(color);
g.drawOval(x, y, r, r);
}
}
Then we rewrite the program. It is possible for people to rewrite with Circle
object in the following way:
import java.awt.*;
import java.awt.Color;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.event.*;
class Test extends JFrame{
private static final Color colors[] = { Color.red, Color.blue,
Color.yellow, Color.orange,
Color.black, Color.white };
private static final int WIDTH = 400,
HEIGHT = 400,
NUMBER_OF_CIRCLES = 1000;
public Test() {
Container contentPane = getContentPane();
JButton button = new JButton("Draw Circle");
final JPanel panel = new JPanel();
contentPane.add(panel, BorderLayout.CENTER);
contentPane.add(button, BorderLayout.SOUTH);
setSize(WIDTH ,HEIGHT);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setVisible(true);
button.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent event) {
Graphics g = panel.getGraphics();
for(int i=0; i < NUMBER_OF_CIRCLES; ++i) {
Circle circle = new Circle(getRandomColor());
circle.draw(g, getRandomX(), getRandomY(), getRandomR());//1000
object created.
}
}
});
}
private int getRandomX() {
return (int)(Math.random()*WIDTH );
}
private int getRandomY() {
return (int)(Math.random()*HEIGHT);
}
private int getRandomR() {
return (int)(Math.random()*(HEIGHT/10));
}
private Color getRandomColor() {
return colors[(int)(Math.random()*colors.length)];
}
public static void main(String[] args) {
Test test = new Test();
}
}
From the above code, you may note that 1000 circle object has been created.
It is memory consuming.
To improve it, we will create a CircleFactory class to customize it by using
flyweight design pattern. Since we just draw circle with different colors, we
can store color info in a hashmap. If a circle has been drawn, the new circle
will be checked with color. If the circle with the same color has been found in
the hashmap, the circle will share the instance which is picked up from the
hashmap instead of creating a new one. We will reuse the object with
different state, that is to say we will share the instance and draw the circle
with different start position and radius on the fly.
class CircleFactory {
//store color
private static final HashMap circleByColor = new HashMap();
public static Circle getCircle(Color color) {
Circle circle = (Circle)circleByColor.get(color);
if(circle == null) {
circle = new Circle(color);
circleByColor.put(color, circle);
System.out.println("Creating " + color + " circle");//see how many
objects we create on command line
}
return circle;
}
}
So our test program will be coded as follows:
import java.awt.*;
import java.util.HashMap;
import java.awt.Color;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.event.*;
28. class Test extends JFrame{
private static final Color colors[] = { Color.red, Color.blue,
Color.yellow, Color.orange,
Color.black, Color.white };
private static final int WIDTH = 400,
HEIGHT = 400,
NUMBER_OF_CIRCLES = 1000;
public Test() {
Container contentPane = getContentPane();
JButton button = new JButton("Draw Circle");
final JPanel panel = new JPanel();
contentPane.add(panel, BorderLayout.CENTER);
contentPane.add(button, BorderLayout.SOUTH);
setSize(WIDTH,HEIGHT);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setVisible(true);
button.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent event) {
Graphics g = panel.getGraphics();
for(int i=0; i < NUMBER_OF_CIRCLES; ++i) {
Circle circle = CircleFactory.getCircle(getRandomColor());
circle.draw(g, getRandomX(),
getRandomY(),getRandomR());
//Since we have 6 different colors, we have 6 objects
created.
}
}
});
}
public static void main(String[] args) {
Test test = new Test();
}
private int getRandomX() {
return (int)(Math.random()*WIDTH );
}
private int getRandomY() {
return (int)(Math.random()*HEIGHT);
}
private int getRandomR() {
return (int)(Math.random()*(HEIGHT/10));
}
private Color getRandomColor() {
return colors[(int)(Math.random()*colors.length)];
}
}
class CircleFactory {
private static final HashMap circleByColor = new HashMap();
public static Circle getCircle(Color color) {
Circle circle = (Circle)circleByColor.get(color);
if(circle == null) {
circle = new Circle(color);
circleByColor.put(color, circle);
System.out.println("Creating " + color + " circle");
}
return circle;
}
}
class Circle {
private Color color;
public Circle(Color color) {
this.color = color;
}
public void draw(Graphics g, int x, int y, int r) {
g.setColor(color);
g.drawOval(x, y, r, r);
}
}
Copy, paste above code and run it. You will see the printout from the
command line, that you only have 6 objects created, not 1000 objects
because you only have 6 colors. Such a big reduction of object
creation will improve your program performance dramatically.
Output :
Creating java.awt.Color[r=255,g=0,b=0] circle
Creating java.awt.Color[r=0,g=0,b=0] circle
Creating java.awt.Color[r=255,g=200,b=0] circle
Creating java.awt.Color[r=255,g=255,b=0] circle
Creating java.awt.Color[r=0,g=0,b=255] circle
Creating java.awt.Color[r=255,g=255,b=255] circle
29.
30. Flyweight design is effective with instantiating a large amount of small and fine-
grained classes by combining with factory design pattern.
If you have jdk1.5 installed, you may need to use a tool to check if you save the
memory by running your commands as follows:
C:> java -Dcom.sun.management.jmxremote Test
And open another console as follows:
C:> jconsole
The jconsole tool will hook up your program Test to give your statistic numbers
about your program, such as threads, heap, memory, VM, etc.
String class is designed with Flyweight design pattern. It has similar structure as above
example. When you create a string constant, such constant is stored in a pool. When
the second string is created, it will be checked to see if it has been created. If it is true,
the second string instance will be picked up from the string pool instead of creating a
new one. This is why the following code makes sense, but bothers many people.
String s1 = "hello";
String s2 = "hello"; //store in a string pool.
String s3 = new String("hello");
System.out.println(s1==s2); //true, share the same memmory address
System.out.println(s1==s3); //false
31. Proxy Pattern
Define proxy pattern
Use a simple object to represent a complex one or provide a placeholder for another object to
control access to it.
The proxy pattern is used when you need to represent a complex with a simpler one. If creation
of object is expensive, its creation can be postponed till the very need arises and till then, a
simple object can represent it. This simple object is called the “Proxy” for the complex object
Where to use & benefits
If creating an object is too expensive in time or memory.
Postpone the creation until you need the actual object.
Load a large image (time consuming).
Load a remote object over network during peak periods.
Access right is required to a complex system.
32. Related patterns include
Adapter pattern, which provides a different interface to the
object it adapts, whereas a proxy provides the same interface as
its subject, and
Decorator pattern, which focuses on adding new functions to an
object, whereas a proxy controls access to the object.
33. Example of proxy pattern
When loading a large image, you may create some light object to
represent it until the image is loaded completely. Usually a proxy
object has the same methods as the object it represents. Once the
object is loaded, it passes on the actual object. For example,
34. abstract class Graphic {
public abstract void load();
public abstract void draw();
...
}
class Image extends Graphic{
public void load() {
...
}
public void draw() {
...
}
...
}
class ImgProxy extends Graphic {
public void load() {
if(image == null) {
image = new Image(filename);
}
...
public void draw() {
...
}
...
}