Lưu ý: lớp này là Singleton hoặc cung cấp một public static method cho việc truy xuất và khởi tạo đối tượng.. Tạo các lớp cụ thể triển khai cùng một giao diện.Rectangle.java public clas
Trang 1HỌC VIỆN CÔNG NGHỆ BƯU CHÍNH VIỄN THÔNG
-
Kiến trúc và thiết kế phần mềm
Hà Nội, tháng 05, năm 2021
1.Factory Pattern:
Trang 2Youtube.com/PoppinKhiem - Sân chơi giới trẻ PTIT
UML
Một Factory Pattern bao gồm các thành phần cơ bản sau:
Super Class: môt supper class trong Factory Pattern có thể là một interface, abstract class hay một class thông thường.
Sub Classes: các sub class sẽ implement các phương thức của supper class theo
nghiệp vụ riêng của nó.
Factory Class: một class chịu tránh nhiệm khởi tạo các đối tượng sub class dựa theo tham số đầu vào Lưu ý: lớp này là Singleton hoặc cung cấp một public static method
cho việc truy xuất và khởi tạo đối tượng Factory class sử dụng if-else hoặc switch-case đểxác định class con đầu ra
Trang 3Tạo các lớp cụ thể triển khai cùng một giao diện.
Rectangle.java
public class Rectangle implements Shape {
@Override
public void draw() {
System.out.println("Inside Rectangle::draw() method.");}
}
Square.java
public class Square implements Shape {
@Override
public void draw() {
System.out.println("Inside Square::draw() method.");}
}
Circle.java
public class Circle implements Shape {
@Override
public void draw() {
System.out.println("Inside Circle::draw() method.");}
}
Bước 3
Tạo một Nhà máy để tạo đối tượng của lớp cụ thể dựa trên thông tin đã cho
ShapeFactory.java
public class ShapeFactory {
//use getShape method to get object of type
shape public Shape getShape(String shapeType){
if(shapeType == null){
return null;
}
if(shapeType.equalsIgnoreCase("CIRCLE"))
{ return new Circle();
} else if(shapeType.equalsIgnoreCase("RECTANGLE")){
return new Rectangle();
Trang 4Youtube.com/PoppinKhiem - Sân chơi giới trẻ PTIT
} else if(shapeType.equalsIgnoreCase("SQUARE")){
return new Square();
public class FactoryPatternDemo {
public static void main(String[] args) {
ShapeFactory shapeFactory = new ShapeFactory();
//get an object of Circle and call its draw method
Shape shape1 = shapeFactory.getShape("CIRCLE");
//call draw method of Circle
shape1.draw();
//get an object of Rectangle and call its draw method
Shape shape2 = shapeFactory.getShape("RECTANGLE");
//call draw method of Rectangle
shape2.draw();
//get an object of Square and call its draw method
Shape shape3 = shapeFactory.getShape("SQUARE");
//call draw method of square
shape3.draw();
}
}
Bước 5
Xác minh kết quả đầu ra
Inside Circle::draw() method
Inside Rectangle::draw() method
Inside Square::draw() method
Trang 52 ABSTRACT FACTORY PATTERN
UML
Một Abstract Factory Pattern bao gồm các thành phần cơ bản sau:
AbstractFactory: Khai báo dạng interface hoặc abstract class chứa các phương thức để
tạo ra các đối tượng abstract
ConcreteFactory: Xây dựng, cài đặt các phương thức tạo các đối tượng cụ thể.
AbstractProduct: Khai báo dạng interface hoặc abstract class để định nghĩa đối tượng abstract.
Product: Cài đặt của các đối tượng cụ thể, cài đặt các phương thức được quy định tại AbstractProduct.
Client: là đối tượng sử dụng AbstractFactory và các AbstractProduct.
Code:
Trang 6Youtube.com/PoppinKhiem - Sân chơi giới trẻ PTIT
public void draw() {
public void draw() {
public void draw() {
System.out.println("Inside Rectangle::draw() method.");
Trang 7abstract Shape getShape(String shapeType) ;
return new Rectangle();
}else if(shapeType.equalsIgnoreCase("SQUARE")){
return new Square();
return new RoundedRectangle();
}else if(shapeType.equalsIgnoreCase("SQUARE")){
return new RoundedSquare();
public class FactoryProducer {
public static AbstractFactory getFactory(boolean rounded){
Trang 8Youtube.com/PoppinKhiem - Sân chơi giới trẻ PTIT
}
}
}
Bước 6
Sử dụng FactoryProductioner để lấy AbstractFactory để lấy các nhà máy của các lớp
cụ thể bằng cách chuyển một thông tin chẳng hạn như loại
AbstractFactoryPatternDemo.java
public class AbstractFactoryPatternDemo
{ public static void main(String[] args)
{
//get shape factory
AbstractFactory shapeFactory =
an object of Shape Rectangle
Shape shape1 = shapeFactory.getShape("RECTANGLE");
//call draw method of Shape Rectangle
shape1.draw();
//get an object of Shape Square
Shape shape2 = shapeFactory.getShape("SQUARE");
//call draw method of Shape Square
shape2.draw();
//get shape factory
AbstractFactory shapeFactory1 =
FactoryProducer.getFactory(true);
//get an object of Shape Rectangle
Shape shape3 = shapeFactory1.getShape("RECTANGLE");
//call draw method of Shape Rectangle
shape3.draw();
//get an object of Shape Square
Shape shape4 = shapeFactory1.getShape("SQUARE");
//call draw method of Shape Square
shape4.draw();
}
}
Bước 7
Xác minh kết quả đầu ra
Inside Rectangle::draw() method
Inside Square::draw() method
Inside RoundedRectangle::draw() method
Inside RoundedSquare::draw() method
Trang 93.Builder Pattern
UML
Một builder gồm các thành phần cơ bản sau:
Product : đại diện cho đối tượng cần tạo, đối tượng này phức tạp, có nhiều thuộc tính.
Builder : là abstract class hoặc interface khai báo phương thức tạo đối tượng.
ConcreteBuilder : kế thừa Builder và cài đặt chi tiết cách tạo ra đối tượng Nó sẽ xác định và nắm giữ các thể hiện mà nó tạo ra, đồng thời nó cũng cung cấp phương thức để trả
các các thể hiện mà nó đã tạo ra trước đó
Director/ Client: là nơi sẽ gọi tới Builder để tạo ra đối tượng.
Code:
Bước 1
Tạo giao diện Mục đại diện cho mặt hàng thực phẩm và đóng gói
Item.java
Trang 10Youtube.com/PoppinKhiem - Sân chơi giới trẻ PTIT
public interface Item {
public String name();
public Packing packing();
public float price();
}
Packing.java
public interface Packing {
public String pack();
public Packing packing() {
return new Wrapper();
}
Trang 11public Packing packing() {
return new Bottle();
public String name() {
return "Veg Burger";
public String name() {
return "Chicken Burger";
}
Trang 12Youtube.com/PoppinKhiem - Sân chơi giới trẻ PTIT
public class Meal {
private List<Item> items = new ArrayList<Item>();public void addItem(Item item){
items.add(item);
}
public float getCost(){
float cost = 0.0f;
Trang 13for (Item item : items) {
cost += item.price();
}
return cost;
}
public void showItems(){
for (Item item : items) {
System.out.print("Item : " + item.name());
System.out.print(", Packing : " + item.packing().pack());System.out.println(", Price : " + item.price());
public class MealBuilder {
public Meal prepareVegMeal (){
Meal meal = new Meal();
meal.addItem(new VegBurger());
meal.addItem(new Coke());
return meal;
}
public Meal prepareNonVegMeal (){
Meal meal = new Meal();
Trang 14Youtube.com/PoppinKhiem - Sân chơi giới trẻ PTIT
public static void main(String[] args) {
MealBuilder mealBuilder = new MealBuilder();
Meal vegMeal = mealBuilder.prepareVegMeal();
System.out.println("Veg Meal");
vegMeal.showItems();
System.out.println("Total Cost: " + vegMeal.getCost());
Meal nonVegMeal = mealBuilder.prepareNonVegMeal();
System.out.println("\n\nNon-Veg Meal");
Item : Veg Burger, Packing : Wrapper, Price : 25.0
Item : Coke, Packing : Bottle, Price : 30.0
Total Cost: 55.0
Non-Veg Meal
Item : Chicken Burger, Packing : Wrapper, Price : 50.5
Item : Pepsi, Packing : Bottle, Price : 35.0
Total Cost: 85.5
4 PROTOTYPE PATTERN UML:
Trang 15Một Prototype Pattern gồm các thành phần cơ bản sau:
Prototype : khai báo một class, interface hoặc abtract class cho việc clone chính nó.
ConcretePrototype class : các lớp này thực thi interface (hoặc kế thừa từ lớp abstract)
được cung cấp bởi Prototype để copy (nhân bản) chính bản thân nó Các lớp này chính là thể hiện cụ thể phương thức clone() Lớp này có thể không cần thiết nếu: Prototype là mộtclass và nó đã implement việc clone chính nó
Client class : tạo mới object bằng cách gọi Prototype thực hiện clone chính nó.
Code:
Bước 1
Tạo một lớp trừu tượng triển khai giao diện Clonable
Shape.java
public abstract class Shape implements Cloneable {
private String id;
protected String type;
abstract void draw();
public String getType(){
Trang 16Youtube.com/PoppinKhiem - Sân chơi giới trẻ PTIT
public Object clone() {
Object clone = null;
public void draw() {
System.out.println("Inside Rectangle::draw() method.");}
Trang 17@Override
public void draw() {
System.out.println("Inside Square::draw() method.");
public void draw() {
System.out.println("Inside Circle::draw() method.");
public class ShapeCache {
private static Hashtable<String, Shape> shapeMap = new
Hashtable<String, Shape>();
public static Shape getShape(String shapeId) {
return (Shape) cachedShape.clone();
}
/ for each shape run database query and create shape
/ shapeMap.put(shapeKey, shape);
/ for example, we are adding three shapes
public static void loadCache() {
Circle circle = new Circle();
circle.setId("1");
shapeMap.put(circle.getId(),circle);
Trang 18Youtube.com/PoppinKhiem - Sân chơi giới trẻ
PrototypePatternDemo sử dụng lớp ShapeCache để lấy bản sao của các hình dạng
được lưu trữ trong Hashtable
PrototypePatternDemo.java
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());}
Trang 19Các thành phần tham gia vào mẫu Proxy Pattern:
Subject : là một interface định nghĩa các phương thực để giao tiếp với client Đối tượng
này xác định giao diện chung cho RealSubject và Proxy để Proxy có thể được sử dụng bất cứ nơi nào mà RealSubject mong đợi
Proxy : là một class sẽ thực hiện các bước kiểm tra và gọi tới đối tượng của class service
thật để thực hiện các thao tác sau khi kiểm tra Nó duy trì một tham chiếu đến RealSubject
để Proxy có thể truy cập nó Nó cũng thực hiện các giao diện tương tự như RealSubject đểProxy có thể được sử dụng thay cho RealSubject Proxy cũng điều khiển truy cập vào RealSubject và có thể tạo hoặc xóa đối tượng này
RealSubject : là một class service sẽ thực hiện các thao tác thực sự Đây là đối tượng
chính mà proxy đại diện
Client : Đối tượng cần sử dụng RealSubject nhưng thông qua Proxy.
Trang 20Youtube.com/PoppinKhiem - Sân chơi giới trẻ PTIT
Tạo các lớp cụ thể triển khai cùng một giao diện
RealImage.java
public class RealImage implements Image {
private String fileName;
public RealImage(String fileName){
this.fileName = fileName;
loadFromDisk(fileName);
}
@Override
public void display() {
System.out.println("Displaying " + fileName);
}
private void loadFromDisk(String fileName){
System.out.println("Loading " + fileName);
}
}
ProxyImage.java
public class ProxyImage implements Image{
private RealImage realImage;
private String fileName;
public ProxyImage(String fileName){
Trang 21public static void main(String[] args) {
Image image = new ProxyImage("test_10mb.jpg");
//image will be loaded from disk
Trang 22Youtube.com/PoppinKhiem - Sân chơi giới trẻ PTIT
Client: đại diện cho khách hàng sử dụng các chức năng thông qua Abstraction.
Abstraction : định ra một abstract interface quản lý việc tham chiếu đến đối tượng hiện thực cụ thể (Implementor).
Refined Abstraction (AbstractionImpl) : hiện thực (implement) các phương thức đã
được định ra trong Abstraction bằng cách sử dụng một tham chiếu đến một đối tượng
của Implementer.
Implementor : định ra các interface cho các lớp hiện thực Thông thường nó là
interface định ra các tác vụ nào đó của Abstraction.
ConcreteImplementor : hiện thực Implementor interface.
Code:
Bước 1
Tạo giao diện trình triển khai cầu nối
DrawAPI.java
public interface DrawAPI {
public void drawCircle(int radius, int x, int y);
public void drawCircle(int radius, int x, int y) {
public void drawCircle(int radius, int x, int y) {
radius + ", x: " + x + ", " + y + "]");
}
}
Trang 23Bước 3
Tạo một hình dạng lớp trừu tượng bằng giao diện DrawAPI
Shape.java
public abstract class Shape
protected DrawAPI drawAPI;
protected Shape(DrawAPI drawAPI){
public class Circle extends Shape {
private int x, y, radius;
public Circle(int x, int y, int radius, DrawAPI drawAPI) {super(drawAPI);
public class BridgePatternDemo {
public static void main(String[] args) {
GreenCircle());
redCircle.draw();
Trang 24Youtube.com/PoppinKhiem - Sân chơi giới trẻ PTIT
greenCircle.draw();
}
}
Bước 6
Xác minh kết quả đầu ra
Drawing Circle[ color: red, radius: 10, x: 100, 100]Drawing Circle[ color: green, radius: 10, x: 100, 100]
7.Singleton Pattern:
UML:
Sử dụng Singleton khi chúng ta muốn:
Đảm bảo rằng chỉ có một instance của lớp
Việc quản lý việc truy cập tốt hơn vì chỉ có một thể hiện duy nhất
Có thể quản lý số lượng thể hiện của một lớp trong giớn hạn chỉ định
Trang 25Bước 1
Tạo một lớp Singleton
SingleObject.java
public class SingleObject {
//create an object of SingleObject
private static SingleObject instance = new SingleObject();
//make the constructor private so that this class cannot
be //instantiated
private SingleObject(){}
//Get the only object available
public static SingleObject getInstance(){
return instance;
}
public void showMessage(){
System.out.println("Hello World!");
public class SingletonPatternDemo {
public static void main(String[] args) {
//illegal construct
//Compile Time Error: The constructor SingleObject() is notvisible
//SingleObject object = new SingleObject();
//Get the only object available
SingleObject object = SingleObject.getInstance();
//show the message
object.showMessage();
}
}
Trang 26Youtube.com/PoppinKhiem - Sân chơi giới trẻ PTIT
Trang 27Tạo lớp cụ thể thực hiện cùng một giao diện.
Circle.java
public class Circle implements Shape
{ private String color;
private int x;
private int y;
private int radius;
public Circle(String color){
public void draw() {
System.out.println("Circle: Draw() [Color : " + color + ", x :
public class ShapeFactory {
/ Uncomment the compiler directive line and
/ javac *.java will compile properly
/ @SuppressWarnings("unchecked")
private static final HashMap circleMap = new HashMap();
public static Shape getCircle(String color) {
Trang 28Youtube.com/PoppinKhiem - Sân chơi giới trẻ PTIT
Circle circle = (Circle)circleMap.get(color);
public class FlyweightPatternDemo {
private static final String colors[] = { "Red", "Green",
"Blue", "White", "Black" };
public static void main(String[] args) {
Trang 30Youtube.com/PoppinKhiem - Sân chơi giới trẻ PTIT
Circle: Draw() [Color : Black, x : 36, y :71, radius :100
Creating circle of color : Green
Circle: Draw() [Color : Green, x : 27, y :27, radius :100
Creating circle of color : White
Circle: Draw() [Color : White, x : 64, y :10, radius :100
Creating circle of color : Red
Circle: Draw() [Color : Red, x : 15, y :44, radius :100
Circle: Draw() [Color : Green, x : 19, y :10, radius :100Circle: Draw() [Color : Green, x : 94, y :32, radius :100Circle: Draw() [Color : White, x : 69, y :98, radius :100
Creating circle of color : Blue
Circle: Draw() [Color : Blue, x : 13, y :4, radius :100
Circle: Draw() [Color : Green, x : 21, y :21, radius :100
Circle: Draw() [Color : Blue, x : 55, y :86, radius :100
Circle: Draw() [Color : White, x : 90, y :70, radius :100
Circle: Draw() [Color : Green, x : 78, y :3, radius :100
Circle: Draw() [Color : Green, x : 64, y :89, radius :100
Circle: Draw() [Color : Blue, x : 3, y :91, radius :100Circle: Draw() [Color : Blue, x : 62, y :82, radius :100
Circle: Draw() [Color : Green, x : 97, y :61, radius :100Circle: Draw() [Color : Green, x : 86, y :12, radius :100Circle: Draw() [Color : Green, x : 38, y :93, radius :100
Circle: Draw() [Color : Red, x : 76, y :82, radius :100Circle: Draw() [Color : Blue, x : 95, y :82, radius :100
9 Adapter Pattern: UML: