0% found this document useful (0 votes)
6 views15 pages

Aoop Skill Week-2.1

The document discusses various design patterns in Java, focusing on the Singleton, Factory, and Abstract Factory patterns. It provides implementations for a License Manager, Banking System Manager, Report Generation, Postfix Expression Evaluation, Vehicle Manufacturing System, and a Logger Management System, illustrating how these patterns enhance flexibility, scalability, and maintainability in software design. Each section includes code examples and explanations of how the design patterns are applied to solve specific problems in application development.

Uploaded by

Alphanso Romany
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)
6 views15 pages

Aoop Skill Week-2.1

The document discusses various design patterns in Java, focusing on the Singleton, Factory, and Abstract Factory patterns. It provides implementations for a License Manager, Banking System Manager, Report Generation, Postfix Expression Evaluation, Vehicle Manufacturing System, and a Logger Management System, illustrating how these patterns enhance flexibility, scalability, and maintainability in software design. Each section includes code examples and explanations of how the design patterns are applied to solve specific problems in application development.

Uploaded by

Alphanso Romany
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/ 15

Aoop Skill Week -2

2300032041
K.NEERAJA

1) In a Java application that requires license validation, explain how you can use
the Singleton Design Pattern to implement a License Manager. Describe the
benefits of using a Singleton for managing the license state and validation
process. Provide a sample implementation of a License Manager class that
ensures only one instance is responsible for checking and managing license
status throughout the application.

package week2
public class License {
private License() {
}
static License l = new License();
static License getL() {
return l;
}
static void validation(boolean x) {
if(x==true) {
System.out.println("Valid license");
} else {
System.out.println("Invalid License");
}
}

}
class LicenseManaging{ public
static void main(String args[]) {
License l1=License.getL();
License.validation(false);
}
}

2) In a Java application for handling banking transactions, how can the


Singleton Design Pattern be used to create a BankingSystemManager?
Explain how this pattern helps ensure there is only one instance managing
banking operations like account balance and transactions. Provide a clear
and simple example of a BankingSystemManager class that uses Singleton
to guarantee a single instance and handle operations safely in a multi-
threaded environment.

package week2;
public class BankingSystem {
private BankingSystem() {
}
static BankingSystem b=new BankingSystem();
static BankingSystem getb() {
return b;
}
void managing() { int
total=10000; int
expenditure=2000; int
balance= total-expenditure; int
transactions= total-balance;
System.out.println("Savings : "+balance);
System.out.println("Money Spent : "+transactions);
}

}
class BankSystemMananging{
public static void main(String args[]){
BankingSystem b1=BankingSystem.getb();
b1.managing();
}

3) In a reporting application, users need to generate reports in different


formats such as PDF, Excel, and HTML. Each report format requires a
different implementation for generating the report. a) Design a
ReportFactory class that uses the Factory Design Pattern to create instances
of the appropriate Report type based on user input. b) Provide the code
implementation for the Report, PDFReport, ExcelReport, and HTMLReport
classes. c) Explain how the Factory Design Pattern helps in managing the
creation of different report types and how it enhances the flexibility and
scalability of the reporting system.
public interface Generatereports {
void reports();
}
class PDFreport implements Generatereports {
public void reports() {
System.out.println("The format is PDF");
}
}
class Excelreport implements Generatereports{
public void reports() {
System.out.println("The format is Excel");
}
}
class Htmlreport implements Generatereports{
public void reports() {
System.out.println("The format is HTML");
}
}
class Factory{ static Generatereports
getObject(int x) { if(x==1) return new
PDFreport(); else if (x==2) return new
Excelreport();
else if (x==3) return new Htmlreport(); else return
null;
}
}
class Demofactory{ public static void
main(String args[]) {
Generatereports gr; gr =
Factory.getObject(2);
gr.reports();
}
}
4) You are tasked with implementing a calculator that evaluates postfix
expressions (Reverse Polish Notation). The postfix expression will be
provided as input, and the output should be the result of the expression. a)
Define an abstract Operation class that represents a generic operation (e.g.,
addition, subtraction, multiplication, division) for evaluating postfix
expressions. Implement concrete classes for each specific operation (e.g.,
Addition, Subtraction, Multiplication, Division). b) Create a OperationFactory
class that uses the Factory Design Pattern to instantiate the appropriate
Operation objects based on the operator encountered in the postfix
expression. c) Implement a PostfixEvaluator class that utilizes the
OperationFactory to evaluate a given postfix expression. The class should
handle the input string (e.g., "7 3 - 2 1 + *") and produce the correct output
(e.g., 12). d) Explain how the Factory Design Pattern is utilized in your
implementation to handle different operations dynamically and how it
contributes to the design's flexibility and maintainability.

package skillweek2;

import java.util.Stack;

abstract class Operation {


public abstract int execute(int operand1, int operand2);
}
class Addition extends Operation {
@Override
public int execute(int operand1, int operand2) {
return operand1 + operand2;
}
}

class Subtraction extends Operation {


@Override
public int execute(int operand1, int operand2) {
return operand1 - operand2;
}
}

class Multiplication extends Operation {


@Override
public int execute(int operand1, int operand2) {
return operand1 * operand2;
}
}

class Division extends Operation {


@Override
public int execute(int operand1, int operand2) {
if (operand2 == 0) {
throw new ArithmeticException("Division by zero");
}
return operand1 / operand2;
}
}

class OperationFactory {
public Operation getOperation(String operator) {
switch (operator) {
case "+":
return new Addition();
case "-":
return new Subtraction();
case "*":
return new Multiplication();
case "/":
return new Division();
default:
throw new IllegalArgumentException("Invalid operator: " +
operator);
}
}
}

class PostfixEvaluator {
private OperationFactory operationFactory;

public PostfixEvaluator() {
this.operationFactory = new OperationFactory();
}

public int evaluate(String expression) {


Stack<Integer> stack = new Stack<>();
String[] tokens = expression.split(" ");

for (String token : tokens) {


if (isOperator(token)) {
int operand2 = stack.pop();
int operand1 = stack.pop();
Operation operation =
operationFactory.getOperation(token); int result =
operation.execute(operand1, operand2); stack.push(result);
} else {
stack.push(Integer.parseInt(token));
}
}
return stack.pop();
}

private boolean isOperator(String token) {


return token.equals("+") || token.equals("-") || token.equals("*") ||
token.equals("/");
}
}

public class PostfixCalculator { public


static void main(String[] args) {
PostfixEvaluator evaluator = new PostfixEvaluator();
String expression = "7 3 - 2 1 + *"; int
result = evaluator.evaluate(expression);
System.out.println("Result of the expression '" + expression + "' is: " +
result);
}
}

5) In the context of developing a sophisticated vehicle manufacturing system


that produces different types of vehicles such as cars, trucks, and
motorcycles, each with its own distinct set of components and assembly
processes, how can the Abstract Factory design pattern be utilized to
manage the creation of these components? a) Design an abstract factory
interface VehicleFactory for this system. What methods should this interface
include to facilitate the creation of components specific to each type of
vehicle? b) Implement concrete factories for each type of vehicle:
CarFactory, TruckFactory, and MotorcycleFactory. Describe the specific
components each factory should produce and how these components differ
from one another. c) Discuss how the Abstract Factory pattern helps in
achieving separation of concerns in the vehicle manufacturing system. What
advantages does it offer in terms of scalability and flexibility when adding
new vehicle types or components? d) Provide a code example of how a
client class can utilize the VehicleFactory interface and its concrete
implementations to assemble a vehicle. Demonstrate how the client can
work with different factories to assemble different types of vehicles without
changing the core logic.

Engine createEngine();
Wheel createWheel();
Body createBody();
}
interface Engine {
String getType();
}
interface Wheel {
String getSize();
}
interface Body {
String getShape();
}
class CarEngine implements Engine {
public String getType() {
return "Car Engine";
}
}
class CarWheel implements Wheel {
public String getSize() { return "17
inch";
}
}
class CarBody implements Body {
public String getShape() {
return "Sedan";
}
}
class TruckEngine implements Engine { public
String getType() {
return "Truck Engine";
}
}
class TruckWheel implements Wheel { public
String getSize() {
return "22 inch";
}
}
class TruckBody implements Body { public
String getShape() {
return "Pickup";
}
}
class MotorcycleEngine implements Engine {
public String getType() {
return "Motorcycle Engine";
}
}
class MotorcycleWheel implements Wheel { public
String getSize() {
return "15 inch";
}
}
class MotorcycleBody implements Body {
public String getShape() { return
"Sport";
}
}
class CarFactory implements VehicleFactory {
public Engine createEngine() {
return new CarEngine();
}
public Wheel createWheel() {
return new CarWheel();
}
public Body createBody() {
return new CarBody();
}
}
class TruckFactory implements VehicleFactory { public
Engine createEngine() {
return new TruckEngine();
}
public Wheel createWheel() {
return new TruckWheel();
}
public Body createBody() {
return new TruckBody();
}
}
class MotorcycleFactory implements VehicleFactory {
public Engine createEngine() {
return new MotorcycleEngine();
}
public Wheel createWheel() {
return new MotorcycleWheel();
}
public Body createBody() {
return new MotorcycleBody();
}
}
class VehicleAssemblyLine {
private VehicleFactory vehicleFactory;
public VehicleAssemblyLine(VehicleFactory vehicleFactory) {
this.vehicleFactory = vehicleFactory;
}
Public void assembleVehicle() {
Engine engine = vehicleFactory.createEngine();
Wheel wheel = vehicleFactory.createWheel();
Body body = vehicleFactory.createBody();
System.out.println("Assembling a vehicle with:");
System.out.println("Engine: " + engine.getType());
System.out.println("Wheel Size: " + wheel.getSize());
System.out.println("Body Shape: " + body.getShape());
}
}
class VehicleManufacturingSystem { public
static void main(String[] args) { VehicleFactory
carFactory = new CarFactory();
VehicleAssemblyLine carAssemblyLine = new
VehicleAssemblyLine(carFactory);
carAssemblyLine.assembleVehicle();
System.out.println();
VehicleFactory truckFactory = new TruckFactory();
VehicleAssemblyLine truckAssemblyLine = new
VehicleAssemblyLine(truckFactory);
truckAssemblyLine.assembleVehicle();
System.out.println();
VehicleFactory motorcycleFactory = new MotorcycleFactory();
VehicleAssemblyLine motorcycleAssemblyLine = new
VehicleAssemblyLine(motorcycleFactory);
motorcycleAssemblyLine.assembleVehicle();
}
}

6) Design a Logger Management System in Java that utilizes both the Singleton
and Factory design patterns. In this system: a) Singleton Pattern: Ensure that
there is only one instance of the LoggerManager class throughout the
application. This class will manage the logging system and provide access to
various types of loggers. b) Factory Pattern: Implement a factory method
within the LoggerManager that creates and returns different types of
loggers (e.g., FileLogger, ConsoleLogger) based on the specified type. In your
design: a) Describe the role of the LoggerManager class and how the
Singleton pattern is applied to it. b) Explain how the Factory pattern is used
within the LoggerManager to create different types of loggers. c) Provide a
code implementation for the LoggerManager class, the Logger interface,
and at least two concrete implementations of loggers (e.g., FileLogger and
ConsoleLogger). d) Discuss how you would use this LoggerManager in a
realworld application to ensure efficient and consistent logging.

package skillweek2;
interface Logger { void
log(String message);
}

class ConsoleLogger implements Logger {


@Override
public void log(String message) {
System.out.println("Console Logger: " + message);
}
}

class FileLogger implements Logger {


@Override
public void log(String message) {

System.out.println("File Logger: " + message);


}
}

class LoggerManager {
private static LoggerManager instance;

private LoggerManager() {}

public static LoggerManager getInstance() {


if (instance == null) {
instance = new LoggerManager();
}
return instance;
}

public Logger createLogger(String type)


{ switch (type.toLowerCase()) {
case "console": return new
ConsoleLogger(); case "file":
return new FileLogger();
default:
throw new IllegalArgumentException("Unknown logger type: " +
type);
}
}
}

public class LoggerManagementSystem { public


static void main(String[] args) {
LoggerManager loggerManager = LoggerManager.getInstance();

Logger consoleLogger = loggerManager.createLogger("console");


consoleLogger.log("This is a log message to the console.");

Logger fileLogger = loggerManager.createLogger("file");


fileLogger.log("This is a log message to the file.");
}
}

You might also like