Tạ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.";
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 2Mộ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àSingletonhoặc cung cấp mộtpublic 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 địnhclass 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 4} 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
Trang 6public void draw() {
System.out.println("Inside RoundedRectangle::draw() method.");}
}
RoundedSquare.java
public class RoundedSquare implements Shape {
@Override
public void draw() {
System.out.println("Inside RoundedSquare::draw() method.");}
}
Rectangle.java
public class Rectangle implements Shape {
@Override
public void draw() {
System.out.println("Inside Rectangle::draw() method.");
Trang 7abstract Shape getShape(String shapeType) ;
public Shape getShape(String shapeType){
if(shapeType.equalsIgnoreCase("RECTANGLE")){
return new Rectangle();
}else if(shapeType.equalsIgnoreCase("SQUARE")){
return new Square();
public Shape getShape(String shapeType){
if(shapeType.equalsIgnoreCase("RECTANGLE")){
return new RoundedRectangle();
}else if(shapeType.equalsIgnoreCase("SQUARE")){
return new RoundedSquare();
public class FactoryProducer {
public static AbstractFactory getFactory(boolean rounded){
Trang 8}
}
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 =
FactoryProducer.getFactory(false);
//get 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áccá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 10public 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 12import java.util.ArrayList;
import java.util.List;
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();
meal.addItem(new ChickenBurger());
meal.addItem(new Pepsi());
Trang 14public 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ó.
protected String type;
abstract void draw();
public String getType(){
Trang 16public 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.");
import java.util.Hashtable;
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();
}
// 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 18Square square = new Square();
square.setId("2");
shapeMap.put(square.getId(),square);
Rectangle rectangle = new Rectangle();
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àoRealSubject 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 20Tạ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){
this.fileName = fileName;
Trang 21public static void main(String[] args) {
Image image = new ProxyImage("test_10mb.jpg");//image will be loaded from disk
image.display();
System.out.println("");
//image will not be loaded from disk
Trang 22 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ượngcủaImplementer.
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) {
System.out.println("Drawing Circle[ color: red, radius: " +
public void drawCircle(int radius, int x, int y) {
System.out.println("Drawing Circle[ color: green, radius: " +
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){
this.drawAPI = drawAPI;
public class Circle extends Shape {
private int x, y, radius;
public Circle(int x, int y, int radius, DrawAPI drawAPI) {
public void draw() {
drawAPI.drawCircle(radius,x,y);
public class BridgePatternDemo {
public static void main(String[] args) {
Shape redCircle = new Circle(100,100, 10, new RedCircle());
Shape greenCircle = new Circle(100,100, 10, new
GreenCircle());
redCircle.draw();
Trang 24}
}
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 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){
this.color = color;
public void setRadius(int radius) {
this.radius = radius;
}
@Override
public void draw() {
System.out.println("Circle: Draw() [Color : " + color + ", x :
import java.util.HashMap;
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 28Circle circle = (Circle)circleMap.get(color);
if(circle == null) {
circle = new Circle(color);
circleMap.put(color, circle);
System.out.println("Creating circle of color : " + color);}
public class FlyweightPatternDemo {
private static final String colors[] = { "Red", "Green", "Blue",
"White", "Black" };
public static void main(String[] args) {
for(int i=0; i < 20; ++i) {
Circle circle =
(Circle)ShapeFactory.getCircle(getRandomColor());
circle.setX(getRandomX());
circle.setY(getRandomY());
circle.setRadius(100);
circle.draw();
}
}
private static String getRandomColor() {
return colors[(int)(Math.random()*colors.length)];
}
private static int getRandomX() {
return (int)(Math.random()*100 );
}
private static int getRandomY() {
return (int)(Math.random()*100);
}
}
Bước 5
Xác minh kết quả đầu ra
Creating circle of color : Black