1. Trang chủ
  2. » Giáo Dục - Đào Tạo

(Tiểu luận) design pattern essay data access object and builder pattern

26 4 0

Đang tải... (xem toàn văn)

Tài liệu hạn chế xem trước, để xem đầy đủ mời bạn chọn Tải xuống

THÔNG TIN TÀI LIỆU

Thông tin cơ bản

Tiêu đề Data Access Object And Builder Pattern
Tác giả Phạm Thành Phong, Phạm Nguyễn Phát Đạt
Người hướng dẫn GV Nguyễn Thanh Phước
Trường học Ton Duc Thang University
Chuyên ngành Information Technology
Thể loại essay
Năm xuất bản 2023
Thành phố Ho Chi Minh City
Định dạng
Số trang 26
Dung lượng 2,62 MB

Nội dung

VIETNAM GENERAL CONFEDERATION OF LABOUR TON DUC THANG UNIVERSITY FACULTY OF INFORMATION TECHNOLOGY DESIGN PATTERN ESSAY DATA ACCESS OBJECT AND BUILDER PATTERN Instructor: GV NGUYỄN THANH PHƯỚC Executor: PHẠM THÀNH PHONG – 520H0399 PHẠM NGUYỄN PHÁT ĐẠT - 520H0348 Course: 24 HO CHI MINH CITY, 2023 VIETNAM GENERAL CONFEDERATION OF LABOUR TON DUC THANG UNIVERSITY FACULTY OF INFORMATION TECHNOLOGY DESIGN PATTERN ESSAY DATA ACCESS OBJECT AND BUILDER PATTERN Instructor: GV NGUYỄN THANH PHƯỚC Executor: PHẠM THÀNH PHONG – 520H0399 PHẠM NGUYỄN PHÁT ĐẠT - 520H0348 Course: 24 HO CHI MINH CITY, 2023 i THANK YOU First, we would like to express our sincere thanks and deep gratitude to Professor Nguyen Thanh Phuoc, who has always supported and guided us wholeheartedly during the research and completion of the report end of term Next, we would like to thank the Department of Information Technology, Ton Duc Thang University for creating conditions for me to study and research this subject The faculty has always been ready to share useful knowledge as well as to share experiences of referencing documents, which helps not only in carrying out and completing research projects but also in learning and training during practice at Ton Duc Thang University in general Finally, after a period of studying in class, we completed the research project thanks to the guidance, help and knowledge learned from the teachers Due to the limitation of knowledge and reasoning ability, the group still has many shortcomings and limitations We would like to ask for your guidance and contributions to make our research more complete Moreover, thanks to the suggestions from teachers and friends, we will complete better in future research papers We hope that all of our teachers and friends - who always care about and support me - are always full of health and peace WE THANK YOU! ii PROJECT COMPLETED AT TON DUC THANG UNIVERSITY I hereby declare that this is my own project and is guided by Mr Nguyen Thanh Phuoc The research contents and results in this topic are honest and have not been published in any form before The data in the tables for analysis, comments and evaluation are collected by the author himself from different sources, clearly stated in the reference section In addition, the project also uses a number of comments, assessments as well as data of other authors, other agencies and organizations, with citations and source annotations If I find any fraud, I will take full responsibility for the content of my project Ton Duc Thang University is not related to copyright and copyright violations caused by me during the implementation process (if any) Ho Chi Minh City, day month year TEACHER'S CONFIRMATION AND ASSESSMENT SECTION The confirmation part of the instructor _ _ _ _ _ _ Ho Chi Minh City, day month year Author (Sign and write full name) The evaluation part of the teacher marks the exam _ _ _ _ _ _ _ Ho Chi Minh City, day month year Author (Sign and write full name) SUMMARY The report is made using the knowledge learned and materials provided by the lecturer, in addition to the reference of documents at Ton Duc Thang University Library Document continues below Discover more from: and design analyze… Đại học Tôn Đức… 54 documents Go to course 49 Social network analysis problems design and analyze… 100% (4) How To Create And 16 Sell Canva Templates design and analyze… 100% (3) Modern Control 200 58 Engineering Solution… design and analyze… 100% (1) Mtk CK - Môn design pattern sử dụng 9… design and analyze… 100% (1) Câu-E - Lecture notes ngsadjkjsojdw Table of Contents design and analyze… None design and analyze… None (28) - hi hello annyong THANK YOU i PROJECT COMPLETED AT TON DUC THANG UNIVERSITY ii SUMMARY LIST OF TABLES, PICTURES, GRAPHS CHAPTER – DATA ACCESS OBJECT PATTERN - Introduction: - Problem: - Solution: - Code example: - Some popular libraries that apply the DAO pattern: 12 - Conclusion: 13 CHAPTER 2: BUILDER PATTERN 14 - Introduction: 14 - Problem: 14 - Solution: 15 - Code example: 16 - Some popular libraries apply builder pattern: 19 REFERENCES 21 LIST OF TABLES, PICTURES, GRAPHS LIST OF PICTURES: Picture DAO architecture Picture Builder Structure 15 REPORT CONTENT CHAPTER – DATA ACCESS OBJECT PATTERN - Introduction: The DAO (Data Access Object) pattern is a software design pattern used in objectoriented programming It is used to separate the application's domain model from the persistence layer by providing a simple, easy-to-use interface for accessing the database The pattern is often used in enterprise-level applications where there are multiple data sources and where data is accessed from multiple locations The DAO pattern is widely used because it provides a high level of abstraction, which makes it easier to manage changes to the data source This is because the data access logic is isolated from the rest of the application, making it easier to update the code when the data source changes In this report, we will explore the problem that DAO pattern solves, the solution that it provides, and provide an example implementation with code snippets - Problem: In many applications, data needs to be accessed and manipulated from different locations within the code This can lead to tight coupling between the domain model and the persistence layer, which makes it difficult to maintain and modify the codebase over time This is especially true when working with complex databases that require complex queries Additionally, when an application uses multiple data sources or changes the data source over time, it can be difficult to update the codebase to reflect these changes Picture 1: DAO architecture In summary, the DAO pattern provides a layer of abstraction between the application's domain model and the persistence layer, which makes it easier to manage changes to the data source and helps to ensure that the application remains consistent over time - Code example: Let's say we have an application that needs to manage a list of users We could define a User class to represent each user in the system, as follows: public class User { private int id; private String name; private String email; // constructor, getters, setters, etc } 10 Next, we would define a DAO interface to provide a set of methods for interacting with the data source In this example, we'll define a UserDao interface with methods for creating, reading, updating, and deleting users: public interface UserDao { public void createUser(User user); public User getUserById(int id); public void updateUser(User user); public void deleteUser(User user); } Next, we would implement the UserDao interface using a concrete DAO class In this example, we'll use JDBC (Java Database Connectivity) to interact with a MySQL database: public class UserJdbcDao implements UserDao { private Connection connection; // constructor, initialize connection, etc public void createUser(User user) { String sql = "INSERT INTO users (name, email) VALUES (?, ?)"; PreparedStatement statement = connection.prepareStatement(sql); statement.setString(1, user.getName()); statement.setString(2, user.getEmail()); statement.executeUpdate(); statement.close(); } public User getUserById(int id) { String sql = "SELECT * FROM users WHERE id = ?"; 11 PreparedStatement statement = connection.prepareStatement(sql); statement.setInt(1, id); ResultSet result = statement.executeQuery(); User user = null; if (result.next()) { user = new User(); user.setId(result.getInt("id")); user.setName(result.getString("name")); user.setEmail(result.getString("email")); } result.close(); statement.close(); return user; } public void updateUser(User user) { String sql = "UPDATE users SET name = ?, email = ? WHERE id = ?"; PreparedStatement statement = connection.prepareStatement(sql); statement.setString(1, user.getName()); statement.setString(2, user.getEmail()); statement.setInt(3, user.getId()); statement.executeUpdate(); statement.close(); } public void deleteUser(User user) { String sql = "DELETE FROM users WHERE id = ?"; PreparedStatement statement = connection.prepareStatement(sql); 12 statement.setInt(1, user.getId()); statement.executeUpdate(); statement.close(); } } Finally, we would use the UserJdbcDao class in our application code to interact with the database Here's an example of how we might use the UserDao interface to create a new user: public class Main { public static void main(String[] args) { UserDao userDao = new UserJdbcDao(); User user = new User(); user.setName("Phat Dat"); user.setEmail("phatdat@gmail.com"); userDao.createUser(user); } } This code would create a new UserJdbcDao instance and use it to create a new user in the database with the name "Phat Dat" and email "phatdat@gmail.com" - Some popular libraries that apply the DAO pattern: Hibernate: Hibernate is a popular ORM (Object-Relational Mapping) framework for Java It uses the DAO pattern to abstract the data access layer from the rest of the application Spring Data: Spring Data is a part of the Spring Framework that provides a unified data access API for working with different data stores, including databases, NoSQL stores, and message brokers It uses the DAO pattern to implement the data access layer 13 MyBatis: MyBatis is a data persistence framework that provides a SQL-based approach to interacting with databases It uses the DAO pattern to provide a layer of abstraction between the application and the database Django: Django is a popular Python web framework that includes an ObjectRelational Mapping (ORM) system for working with databases It uses the DAO pattern to separate the application logic from the database access layer Ruby on Rails: Ruby on Rails is a popular web framework for Ruby It uses the DAO pattern to provide a layer of abstraction between the application and the database - Conclusion: In conclusion, the DAO pattern provides a solution to the problem of managing database operations in an efficient and maintainable manner It separates the data access logic from the business logic and provides a layer of abstraction that simplifies the codebase and makes it more modular The DAO pattern allows developers to easily switch between different data storage mechanisms without affecting the rest of the application In addition, the DAO pattern improves the testability of the codebase, making it easier to write unit tests and integration tests for the data access layer By encapsulating the data access logic, developers can mock or stub the DAO layer when writing tests, without worrying about the underlying database implementation Overall, the DAO pattern is a widely-used design pattern in software development that provides many benefits in terms of code organization, maintainability, and testability By using this pattern, developers can write more robust and scalable applications that are easier to maintain and update over time 14 CHAPTER 2: BUILDER PATTERN - Introduction: The Builder Pattern is a creational design pattern that allows you to create complex objects step-by-step It is often used when you need to create an object with many possible configuration options, and you want to avoid the complexity of a large constructor with many parameters With the Builder Pattern, you can separate the construction of an object from its representation, allowing you to create different representations of the same object This makes the code more flexible and easier to maintain In this report, we will discuss the problem that the Builder Pattern solves, its solution, provide an example, and show some code implementations - Problem: When creating complex objects, you may encounter situations where you have to pass a large number of parameters to the constructor This can make the constructor difficult to use and maintain, especially if the object has many optional parameters For example, imagine you are creating a car object The car has many optional features such as a sunroof, leather seats, a premium sound system, and more You could create a constructor with all of these optional parameters, but that would make the constructor unwieldy and hard to use Plus, if you ever need to add or remove optional features, you would have to change the constructor, which could cause issues if the constructor is used in many places throughout your code This is where the Builder Pattern comes in It allows you to create an object in a step-by-step process, where each step can be optional and flexible 15 - Solution: Picture 2: Builder Structure In this diagram, the key classes and relationships involved in the Builder pattern are: Client: The class that needs to create complex objects It collaborates with the Director to create objects using the Builder interface 16 Director: The class that knows how to use the Builder interface to create complex objects It uses the Builder to construct objects in a step-by-step fashion, and only asks for the final product when it is ready Builder: An interface that defines the steps to create a complex object This interface is implemented by the ConcreteBuilder ConcreteBuilder: A class that implements the Builder interface It knows how to create and assemble the parts of the complex object, and it keeps track of the product it is building Product: The complex object being built It has several parts, each of which may be constructed by the ConcreteBuilder The solution to the problem of complex object creation using the Builder pattern involves creating a hierarchy of classes that work together to create complex objects in a step-by-step fashion The key idea is to separate the construction of the object from its representation, so that the same construction process can create different representations This allows for greater flexibility and reuse, as different representations can be created by using different ConcreteBuilder classes that implement the same Builder interface By using this pattern, we can avoid the complexity of having to create objects with many parameters, and instead use a step-by-step approach that is easier to read, understand, and maintain - Code example: Consider the construction of a home Home is the final end product (object) that is to be returned as the output of the construction process It will have many steps like basement construction, wall construction, and so on roof construction Finally, the whole home object is returned Here using the same process, you can build houses with different properties 17 interface HousePlan { public void setBasement(String basement); public void setStructure(String structure); public void setRoof(String roof); public void setInterior(String interior); } class House implements HousePlan { private String basement; private String structure; private String roof; private String interior; public void setBasement(String basement) { this.basement = basement; } public void setStructure(String structure) { this.structure = structure; } public void setRoof(String roof) { this.roof = roof; } public void setInterior(String interior) { this.interior = interior; } } interface HouseBuilder { public void buildBasement(); public void buildStructure(); public void buildRoof(); public void buildInterior(); public House getHouse(); } class IglooHouseBuilder implements HouseBuilder { private House house; public IglooHouseBuilder() { this.house = new House(); } 18 public void buildBasement() { house.setBasement("Ice Bars"); } public void buildStructure() { house.setStructure("Ice Blocks"); } public void buildInterior() { house.setInterior("Ice Carvings"); } public void buildRoof() { house.setRoof("Ice Dome"); } public House getHouse() { return this.house; } } class TipiHouseBuilder implements HouseBuilder { private House house; public TipiHouseBuilder() { this.house = new House(); } public void buildBasement() { house.setBasement("Wooden Poles"); } public void buildStructure() { house.setStructure("Wood and Ice"); } public void buildInterior() { house.setInterior("Fire Wood"); } public void buildRoof() { house.setRoof("Wood, caribou and seal skins"); } 19 public House getHouse() { return this.house; } } class CivilEngineer { private HouseBuilder houseBuilder; public CivilEngineer(HouseBuilder houseBuilder) { this.houseBuilder = houseBuilder; } public House getHouse() { return this.houseBuilder.getHouse(); } public void constructHouse() { this.houseBuilder.buildBasement(); this.houseBuilder.buildStructure(); this.houseBuilder.buildRoof(); this.houseBuilder.buildInterior(); } } class Builder { public static void main(String[] args) { HouseBuilder iglooBuilder = new IglooHouseBuilder(); CivilEngineer engineer = new CivilEngineer(iglooBuilder); engineer.constructHouse(); House house = engineer.getHouse(); System.out.println("Builder constructed: "+ house); } } - Some popular libraries apply builder pattern: Guava: Guava is a popular Java library that provides various utility classes and functions It uses the Builder pattern in several places, such as constructing instances of the ImmutableList and ImmutableSet classes 20 Apache Commons Lang: Apache Commons Lang is another popular Java library that provides a range of utility classes and functions It uses the Builder pattern to create instances of the EqualsBuilder and HashCodeBuilder classes Lombok: Lombok is a Java library that provides annotations to automatically generate boilerplate code for classes It includes a @Builder annotation that generates a Builder class for a given class Jackson: Jackson is a Java library for serializing and deserializing JSON data It provides a Builder-based API for constructing instances of its ObjectMapper and JsonFactory classes 21 REFERENCES Guru => https://refactoring.guru/design-patterns/builder Viblo => https://viblo.asia/p/builder-design-pattern-6J3ZgjwgKmB Topdev => https://topdev.vn/blog/huong-dan-java-design-pattern-dao/ Head First Design Patterns (ISBN 0-596-00712-4) by Eric Freeman, Elisabeth Freeman, Kathy Sierra and Bert Bates More from: design and analyze… Đại học Tôn Đức… 54 documents Go to course 49 16 200 58 Social network analysis problems design and analyze… 100% (4) How To Create And Sell Canva Templates design and analyze… 100% (3) Modern Control Engineering Solution… design and analyze… 100% (1) Mtk CK - Môn design pattern sử dụng 9… design and analyze… Recommended for you 100% (1) 16 200 How To Create And Sell Canva Templates design and analyze… 100% (3) Modern Control Engineering Solution… design and analyze… 100% (1) Correctional Administration Criminology 96% (113) English - huhu 10 Led hiển thị 100% (3)

Ngày đăng: 19/12/2023, 15:18

TỪ KHÓA LIÊN QUAN

TÀI LIỆU CÙNG NGƯỜI DÙNG

TÀI LIỆU LIÊN QUAN

w