Home> Java> javaTutorial> body text

How to use Java flyweight design pattern to optimize object creation and improve performance and efficiency

王林
Release: 2023-05-12 14:13:06
forward
1040 people have browsed it

Introduction

The Flyweight Pattern in Java is a structural design pattern that aims to reduce memory usage and improve performance by sharing as many objects as possible.

Java Flyweight mode usually includes the following 4 roles

  • Flyweight Factory: Responsible for creating and managing flyweight objects.

  • Concrete Flyweight (Concrete Flyweight): implements the flyweight interface and stores the internal state related to the shared state.

  • Abstract Flyweight (Flyweight): defines the interface that the flyweight object needs to implement Or abstract class.

  • Unshared State: Stores the unshared state of the flyweight object.

Note: Abstract flyweight and non-shared state roles are optional, they can be omitted to merge their functionality into other roles

When the client requests to create or access a flyweight object, the flyweight factory checks whether the flyweight object has already been created Object. If it has been created, a reference to the existing object is returned; if it has not been created, a new object is created and its reference is returned. In this way, clients can share existing objects without having to create new objects, thereby reducing memory usage and improving Performance.

Implementation

Take product information in e-commerce as an example. In e-commerce, each product has a name, price, inventory and other attributes. Normally, each Each product needs to create a separate object, which will increase the memory usage, and if the same product is purchased multiple times, the system will create multiple identical objects, wasting resources.

Abstract Flyweight

public interface Product { String getName(); double getPrice(); int getStock(); }
Copy after login

Specific Flyweight

public class ConcreteProduct implements Product{ private String name; private double price; private int stock; public ConcreteProduct(String name, double price, int stock) { this.name = name; this.price = price; this.stock = stock; } @Override public String getName() { return name; } @Override public double getPrice() { return price; } @Override public int getStock() { return stock; } }
Copy after login

Flyweight Factory

public class ProductFactory { private static Map productMap = new HashMap<>(); public static Product getProduct(String name, double price, int stock) { String key = name + "_" + price; Product res = productMap.get(key); if (Objects.isNull(res)) { // 如果缓存池内不存在,就创建新对象放置到缓存池 res = new ConcreteProduct(name, price, stock); productMap.put(key, res); } return res; } }
Copy after login

Test

public class Demo { public static void main(String[] args) { Product p1 = ProductFactory.getProduct("iPhone 14 Plus", 8899, 1); Product p2 = ProductFactory.getProduct("iPhone 14 Plus", 8899, 1); System.out.println(p1 == p2); } }
Copy after login

How to use Java flyweight design pattern to optimize object creation and improve performance and efficiency

In the above sample code, first create a product interface Product, which contains the name, price, inventory and other attributes of the product. Then create a specific product class ConcreteProduct, implement the Product interface, and define the shared internal states name, price, and stock. Next we create the product factory ProductFactory for Create and manage shared product objects. In this factory, we use HashMap to store shared product objects. Whenever the client needs to purchase a product, we first check whether the product object has been created. If it has been created, return A reference to an existing object. If it has not been created, create a new object and store it in the HashMap and return its reference.

Summary

Advantages

  • ##Reduce The creation of objects saves memory space and improves system performance.

  • By sharing objects, only one copy of the same object in the system can exist in the memory, thereby reducing memory overhead.

  • Improve the scalability of the system. If you need to add new objects, you only need to create them in the factory without modifying the original code.

  • Improve the security of the system. Shared objects are read-only and will not be modified.

Disadvantages

  • may cause the system to It becomes too complex and increases the complexity of the code.

  • Additional work is required to maintain the consistency of shared objects, such as thread safety and other issues need to be considered.

  • The existence of shared objects may reduce the flexibility of the program. For example, the shared objects cannot be personalized.

Application scenarios

  • When there are a large number of identical or similar objects in the system, you can consider using flyweight mode to reduce memory overhead.

  • When objects need to be cached and can be reused , you can also consider using the flyweight mode.

  • In a multi-threaded environment, you can use the flyweight mode to realize object sharing and improve the concurrency performance of the program.

  • In game development, you can use the flyweight model to manage objects such as characters in the game.

The above is the detailed content of How to use Java flyweight design pattern to optimize object creation and improve performance and efficiency. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:yisu.com
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
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!