Nguyễn Chí Cơng
B17DCCN090
Design Pattern
1. Factory method
<<Interface>>
Payment.java
public interface Shape {
void pay();
}
InternetBanking.java
public class InternetBanking implements Shape {
@Override
public void pay() {
System.out.println("Payment method");
}
}
AirPay.java
public class AirPay implements Shape {
@Override
public void pay() {
System.out.println("Payment method");
}
}
VisaCard.java
public class VisaCard implements Shape {
@Override
Nhóm3
public void pay() {
System.out.println("Payment method");
}
}
COD.java
public class COD implements Shape {
@Override
public void pay() {
System.out.println("Payment method");
}
}
PaymentFactory.java
2. Abstract Factory
public class PaymentFactory {
public Shape getPay(String pm){
if(pm == null){
return null;
}
if(pm.equalsIgnoreCase("VISA")){
return new ViSaCard();
} else if(pm.equalsIgnoreCase("COD")){
return new COD();
} else if(pm.equalsIgnoreCase("INTERNETBANKING")){
return new InternetBanking();
} else if(pm.equalsIgnoreCase("AirPay")){
return new AirPay();
}
return null;
}
}
<<Interface>>
Bank.java
public interface Bank {
String getBankName();
}
Agribank.java
public class Agribank implements Bank {
private final String BNAME;
ICICI() {
BNAME = " Agribank BANK";
}
public String getBankName() {
return BNAME;
}
}
BIDV.java
public class BIDV implements Bank {
private final String BNAME;
ICICI() {
BNAME = " BIDV BANK";
}
public String getBankName() {
return BNAME;
}
}
<<Interface>>
Loan.java
Public interface Loan {
protected double rate;
public void getRate(double rate);
}
BussinessLoan.java
public class BussinessLoan extends Loan {
public void getInterestRate(double r) {
rate = r;
}
}
EducationLoan.java
public class EducationLoan extends Loan {
public void getInterestRate(double r) {
rate = r;
}
}
<<abstract>>
AbstractFactory.java
public abstract class AbstractFactory {
public abstract Bank getBank(String bank);
public abstract Loan getLoan(String loan);
}
BankFactory.java
public class BankFactory extends AbstractFactory {
public Bank getBank(String bank) {
if (bank == null) {
return null;
}
if (bank.equalsIgnoreCase("HDFC")) {
return new HDFC();
} else if (bank.equalsIgnoreCase("ICICI"))
{
return new ICICI();
} else if (bank.equalsIgnoreCase("SBI")) {
return new SBI();
}
return null;
}
public Loan getLoan(String loan) {
return null;
}
}
LoanFactory.java
public class LoanFactory extends AbstractFactory {
public Bank getBank(String bank) {
return null;
}
public Loan getLoan(String loan) {
if (loan == null) {
return null;
}
if (loan.equalsIgnoreCase("Home")) {
return new HomeLoan();
} else if
(loan.equalsIgnoreCase("Business")) {
return new BussinessLoan();
} else if
(loan.equalsIgnoreCase("Education")) {
return new EducationLoan();
}
return null;
}
}
FactoryProducer.java
public class FactoryProducer {
public static AbstractFactory
getFactory(String choice) {
if (choice.equalsIgnoreCase("Bank")) {
return new BankFactory();
} else if
(choice.equalsIgnoreCase("Loan")) {
return new LoanFactory();
}
return null;
}
}
Abstract
FactoryPatternDemo.java
public class AbstractFactoryPatternDemo {
public static void main(String args[]) throws
IOException {
BufferedReader br = new BufferedReader(new
InputStreamReader(System.in));
System.out.print("Nhap ten cua Bank ma ban muon
vay tien: ");
String bankName = br.readLine();
System.out.print("Nhap kieu ban muon vay (home,
business, education): ");
String loanName = br.readLine();
AbstractFactory bankFactory =
FactoryCreator.getFactory("Bank");
Bank b = bankFactory.getBank(bankName);
System.out.print("Nhap lai suat ngan hang " +
b.getBankName() + ": ");
double rate = Double.parseDouble(br.readLine());
System.out.print("Nhap so tien ban muon vay:
");
double loanAmount =
Double.parseDouble(br.readLine());
System.out.print("Nhap so nam de thanh toan
toan bo so tien ban vay: ");
int years = Integer.parseInt(br.readLine());
System.out.println("Ban dang vay tien tu " +
b.getBankName());
AbstractFactory loanFactory =
FactoryCreator.getFactory("Loan");
Loan loan = loanFactory.getLoan(loanName);
loan.getInterestRate(rate);
loan.calculateLoanPayment(loanAmount, years);
}
}
3. Builder
Order.java
public class Order {
private OrderType orderType;
private BreadType breadType;
private SauceType sauceType;
private VegetableType vegetableType;
public Order(OrderType orderType, BreadType
breadType, SauceType sauceType, VegetableType
vegetableType) {
super();
this.orderType = orderType;
this.breadType = breadType;
this.sauceType = sauceType;
this.vegetableType = vegetableType;
}
@Override
public String toString() {
return "Order [orderType=" + orderType +
", breadType=" + breadType + ", sauceType=" +
sauceType
+ ", vegetableType=" +
vegetableType + "]";
}
public OrderType getOrderType() {
return orderType;
}
public BreadType getBreadType() {
return breadType;
}
public SauceType getSauceType() {
return sauceType;
}
public VegetableType getVegetableType() {
return vegetableType;
}
}
public enum BreadType {
SIMPLE, OMELETTE, FRIED_EGG, GRILLED_FISH,
PORK, BEEF,
}
public enum OrderType {
ON_SITE, TAKE_AWAY;
}
public enum SauceType {
SOY_SAUCE, FISH_SAUCE, OLIVE_OIL, KETCHUP,
MUSTARD;
}
public enum VegetableType {
SALAD, CUCUMBER, TOMATO
}
<<Interface>>
OrderBuilder
public interface OrderBuilder {
OrderBuilder orderType(OrderType orderType);
OrderBuilder orderBread(BreadType breadType);
OrderBuilder orderSauce(SauceType sauceType);
OrderBuilder orderVegetable(VegetableType
vegetableType);
Order build();
}
FastFoodOrderBuilde
r.java
public class FastFoodOrderBuilder implements
OrderBuilder {
private OrderType orderType;
private BreadType breadType;
private SauceType sauceType;
private VegetableType vegetableType;
@Override
public OrderBuilder orderType(OrderType
orderType) {
this.orderType = orderType;
return this;
}
@Override
public OrderBuilder orderBread(BreadType
breadType) {
this.breadType = breadType;
return this;
}
@Override
public OrderBuilder orderSauce(SauceType
sauceType) {
this.sauceType = sauceType;
return this;
}
@Override
public OrderBuilder
orderVegetable(VegetableType vegetableType) {
this.vegetableType = vegetableType;
return this;
}
@Override
public Order build() {
return new Order(orderType, breadType,
sauceType, vegetableType);
}
}
Client.java
public class Client {
public static void main(String[] args) {
Order order = new FastFoodOrderBuilder()
.orderType(OrderType.ON_SITE).orderBread(Bread
Type.OMELETTE)
.orderSauce(SauceType.SOY_SAUCE).build();
System.out.println(order);
}
}
4. Adapter
interface MediaPlayer
public interface MediaPlayer {
public void play(String audioType, String
fileName);
}
interface
AdvancedMediaPlayer
public interface AdvancedMediaPlayer {
public void playVlc(String fileName);
public void playMp4(String fileName);
}
VlcPlayer
public class VlcPlayer implements
AdvancedMediaPlayer{
@Override
public void playVlc(String fileName) {
System.out.println("Playing vlc file.
Name: "+ fileName);
}
@Override
public void playMp4(String fileName) {
//do nothing
}
}
Mp4Player
public class Mp4Player implements
AdvancedMediaPlayer{
@Override
public void playVlc(String fileName) {
//do nothing
}
@Override
public void playMp4(String fileName) {
System.out.println("Playing mp4 file.
Name: "+ fileName);
}
}
MediaAdapter
public class MediaAdapter implements
MediaPlayer {
AdvancedMediaPlayer advancedMusicPlayer;
public MediaAdapter(String audioType){
if(audioType.equalsIgnoreCase("vlc") )
{
advancedMusicPlayer = new
VlcPlayer();
}else if
(audioType.equalsIgnoreCase("mp4")){
advancedMusicPlayer = new
Mp4Player();
}
}
@Override
public void play(String audioType, String
fileName) {
if(audioType.equalsIgnoreCase("vlc")){
advancedMusicPlayer.playVlc(fileName);
}
else
if(audioType.equalsIgnoreCase("mp4")){
advancedMusicPlayer.playMp4(fileName);
}
}
}
AudioPlayer
public class AudioPlayer implements
MediaPlayer {
MediaAdapter mediaAdapter;
@Override
public void play(String audioType, String
fileName) {
//inbuilt support to play mp3 music
files
if(audioType.equalsIgnoreCase("mp3")){
System.out.println("Playing mp3
file. Name: " + fileName);
}
//mediaAdapter is providing support to
play other file formats
else
if(audioType.equalsIgnoreCase("vlc") ||
audioType.equalsIgnoreCase("mp4")){
mediaAdapter = new
MediaAdapter(audioType);
mediaAdapter.play(audioType,
fileName);
}
else{
System.out.println("Invalid media.
" + audioType + " format not supported");
}
}
}
AdapterPatternDemo
public class AdapterPatternDemo {
public static void main(String[] args) {
AudioPlayer audioPlayer = new
AudioPlayer();
audioPlayer.play("mp3", "beyond the
horizon.mp3");
audioPlayer.play("mp4", "alone.mp4");
audioPlayer.play("vlc", "far far
away.vlc");
audioPlayer.play("avi", "mind
me.avi");
}
}
5. Singleton
public class Filelogger implements Logger{
private static FileLogger logger;
private FileLogger(){
}
public static Filellogger getFileLogger(){
if (logger == null){
logger = new FileLogger();
}
return logger;
}
public synchronized void log(String msg){
FileUtile futil = new FileUtil();
Futil.writeToFile(“log.txt”, msg, true, true);
}
public class LoggerFactory {
public boolean isFileLoggingEnabled() {
Properties p = new Properties();
try {
p.load(ClassLoader.getSystemResourceAsStream(
"Logger.properties"));
String fileLoggingValue =
p.getProperty("FileLogging");
if (fileLoggingValue.equalsIgnoreCase("ON") == true)
return true;
else
return false;
} catch (IOException e) {
return false;
}
}
//Factory Method
public Logger getLogger() {
if (isFileLoggingEnabled()) {
return new FileLogger();
} else {
return new ConsoleLogger();
}
}
}
6. Prototype
Shape
public abstract class Shape implements
Cloneable {
private String id;
protected String type;
abstract void draw();
public String getType(){
return type;
}
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public Object clone() {
Object clone = null;
try {
clone = super.clone();
} catch (CloneNotSupportedException
e) {
e.printStackTrace();
}
}
return clone;
}
Rectangle
public class Rectangle extends Shape {
public Rectangle(){
type = "Rectangle";
}
@Override
public void draw() {
System.out.println("Inside
Rectangle::draw() method.");
}
}
Square
public class Square extends Shape {
public Square(){
type = "Square";
}
@Override
public void draw() {
System.out.println("Inside
Square::draw() method.");
}
}
Circle
public class Circle extends Shape {
public Circle(){
type = "Circle";
}
@Override
public void draw() {
System.out.println("Inside
Circle::draw() method.");
}
}
ShapeCache
public class ShapeCache {
private static Hashtable<String, Shape>
shapeMap = new Hashtable<String, Shape>();
public static Shape getShape(String
shapeId) {
Shape cachedShape =
shapeMap.get(shapeId);
return (Shape) cachedShape.clone();
}
public static void loadCache() {
Circle circle = new Circle();
circle.setId("1");
shapeMap.put(circle.getId(),circle);
Square square = new Square();
square.setId("2");
shapeMap.put(square.getId(),square);
Rectangle rectangle = new
Rectangle();
rectangle.setId("3");
shapeMap.put(rectangle.getId(),
rectangle);
}
}
PrototypePatternDemo
public class PrototypePatternDemo {
public static void main(String[] args) {
ShapeCache.loadCache();
Shape clonedShape = (Shape)
ShapeCache.getShape("1");
System.out.println("Shape : " +
clonedShape.getType());
Shape clonedShape2 = (Shape)
ShapeCache.getShape("2");
System.out.println("Shape : " +
clonedShape2.getType());
Shape clonedShape3 = (Shape)
ShapeCache.getShape("3");
System.out.println("Shape : " +
clonedShape3.getType());
}
}
7. Proxy
public interface Image {
public void process();
}
public class JPGImage implements Image {
public void process() {
System.out.print("JPG Image");
}
}
public class GIFImage implements Image {
public void process() {
System.out.print("GIF Image");
}
}
public class ImageProxy implements Image {
private Image image;
public void process() {
if (image == null)
image = new JPGImage();//tạo đối tượng ảnh JPG, chỉ
mang tính minh họa
image.process();
}
}
8. Composite
public interface TaskItem{
public double getTime();
}
public class Project implements TaskItem{
private String name;
private ArrayList subtask = new ArrayList();
public Project(){ }
public Project(String newName){
name = newName;
}
public String getName(){
return name; }
public ArrayList getSubtasks(){ return subtask; }
public double getTime(){
double totalTime = 0;
Iterator items = subtask.iterator();
while(items.hasNext()){
TaskItem item = (TaskItem)items.next();
totalTime += item.getTime();
}
return totalTime;
}
public void setName(String newName){ name = newName; }
public void addTaskItem(TaskItem element){
if (!subtask.contains(element)){
subtask.add(element);
}
}
public void removeTaskItem(TaskItem element){
subtask.remove(element);
}
}
public class Task implements TaskItem{
private String name;
private double time;
public Task(){ }
public Task(String newName, double newTimeRequired){
name = newName;
time = newTimeRequired;
}
public String getName(){ return name; }
public double getTime(){
return time;
}
public void setName(String newName){ name = newName; }
public void setTime(double newTimeRequired){ time =
newTimeRequired; }
}
9. Bridge
Account.java
public interface Account {
void openAccount();
}
CheckingAccount
public class CheckingAccount implements Account {
@Override
public void openAccount() {
System.out.println("Checking Account");
}
}
SavingAccount
public class SavingAccount implements Account {
@Override
public void openAccount() {
System.out.println("Saving Account");
}
}
Abstract class
Bank.java
public abstract class Bank {
protected Account account;
public Bank(Account account) {
this.account = account;
}
public abstract void openAccount();
}
VietcomBank.java
public class VietcomBank extends Bank {
public VietcomBank(Account account) {
super(account);
}
@Override
public void openAccount() {
System.out.print("Open your account at
VietcomBank is a ");
account.openAccount();
}
}
TPBank.java
public class TPBank extends Bank {
public TPBank(Account account) {
super(account);
}
@Override
public void openAccount() {
System.out.print("Open your account at TPBank
is a ");
account.openAccount();
}
}
10. Decorator
<<interface>> Window
interface Window {
public void draw(); // draws the Window
public String getDescription(); // returns
a description of the Window
}
SimpleWindow.java
class SimpleWindow implements Window {
public void draw() {
// draw window
}
public String getDescription() {
return "simple window";
}
}