Table of Contents
Preface
Builder Pattern
Introduction
Prototype Pattern
Home Java javaTutorial Introduction to Builder Pattern and Prototype Pattern in Java Design Patterns (Code Example)

Introduction to Builder Pattern and Prototype Pattern in Java Design Patterns (Code Example)

Sep 12, 2018 pm 03:58 PM
java Prototype pattern

This article brings you an introduction to the builder pattern and prototype pattern in Java design patterns (code examples). It has certain reference value. Friends in need can refer to it. I hope it will be helpful to you. help.

Preface

In the previous article we learned about the factory pattern and introduced the simple factory pattern, factory method and abstract factory pattern. This article introduces the builder pattern and prototype pattern, which are creative patterns in design patterns.

Builder Pattern

Introduction

The builder pattern is a creational pattern. The builder pattern uses multiple simple objects to build a complex object step by step. This type of design pattern is a creational pattern, which provides an optimal way to create objects.
To put it simply, it is to extract a complex thing and provide a simple call to the outside world, which can create different representations in the same construction process. It is very similar to the factory mode, but it pays more attention to the assembly of components.

Here is an example to illustrate.
The food we eat every day includes pancakes, lunch boxes, ramen, soy milk, milk and juice. It is divided into three meals, breakfast, lunch and dinner. The meals mainly include food (commonly known as rice) and drink (soy milk, juice, etc.), then we can have pancakes and soy milk as breakfast, and box lunch and juice as lunch, so We can know exactly what to eat for breakfast and lunch.

First we define a food category with two attributes, food and drink.

class Meal{
    private String food;
    private String drinks;
    
    public String getFood() {
        return food;
    }
    public void setFood(String food) {
        this.food = food;
    }
    
    public String getDrinks() {
        return drinks;
    }
    public void setDrinks(String drinks) {
        this.drinks = drinks;
    }
}
Copy after login

When we define food, we are defining a standard interface for food. What does a piece of food contain? In fact, it means eating and drinking.

interface IBuilderFood{
    void buildFood();
    void buildDrinks();
    Meal createMeal();
}
Copy after login

The food interface defines an eating and a drinking component, and then returns the food we need through the createMeal() method.
So now we can define a breakfast and lunch.
Code example:

class Breakfast implements IBuilderFood{
    Meal meal;

    public Breakfast(){
        meal=new Meal();
    }
    
    @Override
    public void buildFood() {
        meal.setFood("煎饼");
    }

    @Override
    public void buildDrinks() {
        meal.setDrinks("豆浆");   
    }
    
    @Override
    public Meal createMeal() {
        return meal;
    }
}

class Lunch implements IBuilderFood{
    Meal meal;

    public Lunch(){
        meal=new Meal();
    }
    
    @Override
    public void buildFood() {
        meal.setFood("盒饭");
    }

    @Override
    public void buildDrinks() {
        meal.setDrinks("果汁");   
    }
    
    @Override
    public Meal createMeal() {
        return meal;
    }
}
Copy after login

After the definition, the process of creating breakfast and lunch is complete. But this is not the builder mode. It has a core Director, which is used to create parts of complex objects, create the parts completely or create them according to certain rules. So here we can create a Director to create a meal. As for what meal is created, it does not need to know, this is decided by the caller.

Here we can define a restaurant and create a meal. The customer decides what meal to create.
Code example:

class FoodStore{
    public Meal createBreakfast(IBuilderFood bf){
        bf.buildDrinks();
        bf.buildFood();
        return bf.createMeal();
    }
}
Copy after login

After creating this Director, we will call the test again.

Code example:

public class BuilderTest {

    public static void main(String[] args) {
        FoodStore foodStore=new FoodStore();
        Meal meal=foodStore.createBreakfast(new Breakfast());
        Meal meal2=foodStore.createBreakfast(new Lunch());
        System.out.println("小明早上吃的是:"+meal.getFood()+",喝的饮料是:"+meal.getDrinks());
        System.out.println("小明中午吃的是:"+meal2.getFood()+",喝的饮料是:"+meal2.getDrinks()); 
    }

}
Copy after login

Output result:

小明早上吃的是:煎饼,喝的饮料是:豆浆
小明中午吃的是:盒饭,喝的饮料是:果汁
Copy after login

Briefly introduces the operating principle of the builder mode. It can be summarized as these 4 points:

  1. Builder: Specifies an abstract interface, stipulates the creation of the required implementation components for the product, and does not involve the creation of specific object components.

  2. ConcreteBuilder: It is necessary to implement the Builder interface, and create different methods for different logics, and finally provide an instance of the product.

  3. Director: Used to create the part of complex objects. Create this part completely or according to certain rules.

  4. Product: Indicates the constructed complex object.

Usage scenarios:
Applicable when some basic components are inconvenient, but the combination changes frequently. For example, a supermarket promotion gift package.

Advantages:

  1. The builder is independent and easy to expand.

  2. Easy to control detailed risks.

Disadvantages

  1. The internal structure is complex and difficult to understand.

  2. The products directly need to have something in common and the scope should be controlled.

Prototype Pattern

The Prototype Pattern (Prototype Pattern) is used to create repeated objects while ensuring performance. This type of design pattern is a creational pattern, which provides an optimal way to create objects.

Generally speaking, when we create an object, we create it directly. However, when the cost of creating the object is high, repeated creation is not cost-effective. In this case, we can use the prototype mode.
For example, we have all sent emails. During festivals, we usually send blessings. Most of these blessings are the same except for the names. At this time we can use this mode to create accordingly.

Here is a simple example to illustrate.
Xiao Ming and Xiao Hong have their birthdays on the same day, so we need to send them emails to wish them well, but because we are lazy, the blessing words are the same except for their names. At this time, we can first complete the writing of the blessing, then clone the blessing, and finally send it according to different names. But I’ll keep it simple here, just print it out.

Code example:

public class PrototypeTest {

    public static void main(String[] args) {
        Mail mail=new Mail();
        mail.setMsg("生日快乐!");
        Mail mail2=(Mail) mail.clone();
        mail.setName("小明");
        mail2.setName("小红");
        System.out.println(mail.toString());
        System.out.println(mail2.toString());
    }
}

 class Mail implements Cloneable {
    private String name;
    private String msg;
    
    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }
    public String getMsg() {
        return msg;
    }

    public void setMsg(String msg) {
        this.msg = msg;
    }
    public Object clone() {
        Object clone = null;
        try {
            clone = super.clone();
        } catch (CloneNotSupportedException e) {
            e.printStackTrace();
        }
        return clone;
    }

    @Override
    public String toString() {
        return name + ":" + msg ;
    }
    
}
Copy after login

Output result:

小明:生日快乐!
小红:生日快乐!
Copy after login

看完原型模式的创建,是不是感觉就是和Java中克隆即为类似呢?
实际上它的核心也就是克隆。
克隆有两种,浅克隆和深克隆,本文主要介绍的是浅克隆。
浅克隆:

在浅克隆中,如果原型对象的成员变量是值类型,将复制一份给克隆对象;如果原型对象的成员变量是引用类型,则将引用对象的地址复制一份给克隆对象,也就是说原型对象和克隆对象的成员变量指向相同的内存地址。
简单来说,在浅克隆中,当对象被复制时只复制它本身和其中包含的值类型的成员变量,而引用类型的成员对象并没有复制。
实现Cloneable接口并重写Object类中的clone()方法;

深克隆:

在深克隆中,无论原型对象的成员变量是值类型还是引用类型,都将复制一份给克隆对象,深克隆将原型对象的所有引用对象也复制一份给克隆对象。

简单来说,在深克隆中,除了对象本身被复制外,对象所包含的所有成员变量也将复制。
实现Serializable接口,通过对象的序列化和反序列化实现克隆,可以实现真正的深度克隆。

使用场景:

  1. 类初始化的时候需要消耗大量资源的时候;

  2. 获取数据库连接繁琐的时候;

  3. 一个对象,有很多个修改者的时候;

优点:
1.可以提升性能;

缺点:
1.因为必须实现Cloneable 接口,所以用起来可能不太方便。

相关推荐:

Java设计模式中工厂模式的介绍(代码示例)

Java设计模式是什么?Java设计模式中单例模式的介绍

The above is the detailed content of Introduction to Builder Pattern and Prototype Pattern in Java Design Patterns (Code Example). For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Java Spring Interview Questions Java Spring Interview Questions Aug 30, 2024 pm 04:29 PM

In this article, we have kept the most asked Java Spring Interview Questions with their detailed answers. So that you can crack the interview.

Break or return from Java 8 stream forEach? Break or return from Java 8 stream forEach? Feb 07, 2025 pm 12:09 PM

Java 8 introduces the Stream API, providing a powerful and expressive way to process data collections. However, a common question when using Stream is: How to break or return from a forEach operation? Traditional loops allow for early interruption or return, but Stream's forEach method does not directly support this method. This article will explain the reasons and explore alternative methods for implementing premature termination in Stream processing systems. Further reading: Java Stream API improvements Understand Stream forEach The forEach method is a terminal operation that performs one operation on each element in the Stream. Its design intention is

TimeStamp to Date in Java TimeStamp to Date in Java Aug 30, 2024 pm 04:28 PM

Guide to TimeStamp to Date in Java. Here we also discuss the introduction and how to convert timestamp to date in java along with examples.

PHP: A Key Language for Web Development PHP: A Key Language for Web Development Apr 13, 2025 am 12:08 AM

PHP is a scripting language widely used on the server side, especially suitable for web development. 1.PHP can embed HTML, process HTTP requests and responses, and supports a variety of databases. 2.PHP is used to generate dynamic web content, process form data, access databases, etc., with strong community support and open source resources. 3. PHP is an interpreted language, and the execution process includes lexical analysis, grammatical analysis, compilation and execution. 4.PHP can be combined with MySQL for advanced applications such as user registration systems. 5. When debugging PHP, you can use functions such as error_reporting() and var_dump(). 6. Optimize PHP code to use caching mechanisms, optimize database queries and use built-in functions. 7

Java Program to Find the Volume of Capsule Java Program to Find the Volume of Capsule Feb 07, 2025 am 11:37 AM

Capsules are three-dimensional geometric figures, composed of a cylinder and a hemisphere at both ends. The volume of the capsule can be calculated by adding the volume of the cylinder and the volume of the hemisphere at both ends. This tutorial will discuss how to calculate the volume of a given capsule in Java using different methods. Capsule volume formula The formula for capsule volume is as follows: Capsule volume = Cylindrical volume Volume Two hemisphere volume in, r: The radius of the hemisphere. h: The height of the cylinder (excluding the hemisphere). Example 1 enter Radius = 5 units Height = 10 units Output Volume = 1570.8 cubic units explain Calculate volume using formula: Volume = π × r2 × h (4

PHP vs. Python: Understanding the Differences PHP vs. Python: Understanding the Differences Apr 11, 2025 am 12:15 AM

PHP and Python each have their own advantages, and the choice should be based on project requirements. 1.PHP is suitable for web development, with simple syntax and high execution efficiency. 2. Python is suitable for data science and machine learning, with concise syntax and rich libraries.

Create the Future: Java Programming for Absolute Beginners Create the Future: Java Programming for Absolute Beginners Oct 13, 2024 pm 01:32 PM

Java is a popular programming language that can be learned by both beginners and experienced developers. This tutorial starts with basic concepts and progresses through advanced topics. After installing the Java Development Kit, you can practice programming by creating a simple "Hello, World!" program. After you understand the code, use the command prompt to compile and run the program, and "Hello, World!" will be output on the console. Learning Java starts your programming journey, and as your mastery deepens, you can create more complex applications.

How to Run Your First Spring Boot Application in Spring Tool Suite? How to Run Your First Spring Boot Application in Spring Tool Suite? Feb 07, 2025 pm 12:11 PM

Spring Boot simplifies the creation of robust, scalable, and production-ready Java applications, revolutionizing Java development. Its "convention over configuration" approach, inherent to the Spring ecosystem, minimizes manual setup, allo

See all articles