Compare commits

..

2 Commits

25 changed files with 1 additions and 1847 deletions

View File

@ -1460,15 +1460,6 @@
"contributions": [
"code"
]
},
{
"login": "zWeBrain",
"name": "zWeBrain",
"avatar_url": "https://avatars.githubusercontent.com/u/46642512?v=4",
"profile": "https://github.com/zWeBrain",
"contributions": [
"code"
]
}
],
"contributorsPerLine": 4,

View File

@ -10,7 +10,7 @@
[![Coverage](https://sonarcloud.io/api/project_badges/measure?project=iluwatar_java-design-patterns&metric=coverage)](https://sonarcloud.io/dashboard?id=iluwatar_java-design-patterns)
[![Join the chat at https://gitter.im/iluwatar/java-design-patterns](https://badges.gitter.im/Join%20Chat.svg)](https://gitter.im/iluwatar/java-design-patterns?utm_source=badge&utm_medium=badge&utm_campaign=pr-badge&utm_content=badge)
<!-- ALL-CONTRIBUTORS-BADGE:START - Do not remove or modify this section -->
[![All Contributors](https://img.shields.io/badge/all_contributors-161-orange.svg?style=flat-square)](#contributors-)
[![All Contributors](https://img.shields.io/badge/all_contributors-160-orange.svg?style=flat-square)](#contributors-)
<!-- ALL-CONTRIBUTORS-BADGE:END -->
<br/>
@ -315,9 +315,6 @@ This project is licensed under the terms of the MIT license.
<td align="center"><a href="https://www.linkedin.com/in/jinisha-vora"><img src="https://avatars.githubusercontent.com/u/40777762?v=4?s=100" width="100px;" alt=""/><br /><sub><b>jinishavora</b></sub></a><br /><a href="https://github.com/iluwatar/java-design-patterns/pulls?q=is%3Apr+reviewed-by%3Ajinishavora" title="Reviewed Pull Requests">👀</a> <a href="https://github.com/iluwatar/java-design-patterns/commits?author=jinishavora" title="Code">💻</a></td>
<td align="center"><a href="https://github.com/eas5"><img src="https://avatars.githubusercontent.com/u/50836521?v=4?s=100" width="100px;" alt=""/><br /><sub><b>Elvys Soares</b></sub></a><br /><a href="https://github.com/iluwatar/java-design-patterns/commits?author=eas5" title="Code">💻</a></td>
</tr>
<tr>
<td align="center"><a href="https://github.com/zWeBrain"><img src="https://avatars.githubusercontent.com/u/46642512?v=4?s=100" width="100px;" alt=""/><br /><sub><b>zWeBrain</b></sub></a><br /><a href="https://github.com/iluwatar/java-design-patterns/commits?author=zWeBrain" title="Code">💻</a></td>
</tr>
</table>
<!-- markdownlint-restore -->

View File

@ -1,122 +0,0 @@
---
layout: pattern
title: Composite Entity
folder: composite-entity
permalink: /patterns/composite-entity/
categories: Structural
tags:
- Enterprise Integration Pattern
---
## Intent
It is used to model, represent, and manage a set of persistent objects that are interrelated, rather than representing them as individual fine-grained entities.
## Explanation
Real world example
> For a console, there may be many interfaces that need to be managed and controlled. Using the composite entity pattern, dependent objects such as messages and signals can be combined together and controlled using a single object.
In plain words
> Composite entity pattern allows a set of related objects to be represented and managed by a unified object.
**Programmatic Example**
We need a generic solution for the problem. To achieve this, let's introduce a generic
Composite Entity Pattern.
```java
public abstract class DependentObject<T> {
T data;
public void setData(T message) {
this.data = message;
}
public T getData() {
return data;
}
}
public abstract class CoarseGrainedObject<T> {
DependentObject<T>[] dependentObjects;
public void setData(T... data) {
IntStream.range(0, data.length).forEach(i -> dependentObjects[i].setData(data[i]));
}
public T[] getData() {
return (T[]) Arrays.stream(dependentObjects).map(DependentObject::getData).toArray();
}
}
```
The specialized composite entity `console` inherit from this base class as follows.
```java
public class MessageDependentObject extends DependentObject<String> {
}
public class SignalDependentObject extends DependentObject<String> {
}
public class ConsoleCoarseGrainedObject extends CoarseGrainedObject<String> {
@Override
public String[] getData() {
super.getData();
return new String[]{
dependentObjects[0].getData(), dependentObjects[1].getData()
};
}
public void init() {
dependentObjects = new DependentObject[]{
new MessageDependentObject(), new SignalDependentObject()};
}
}
public class CompositeEntity {
private final ConsoleCoarseGrainedObject console = new ConsoleCoarseGrainedObject();
public void setData(String message, String signal) {
console.setData(message, signal);
}
public String[] getData() {
return console.getData();
}
}
```
Now managing the assignment of message and signal objects with the composite entity `console`.
```java
var console = new CompositeEntity();
console.init();
console.setData("No Danger", "Green Light");
Arrays.stream(console.getData()).forEach(LOGGER::info);
console.setData("Danger", "Red Light");
Arrays.stream(console.getData()).forEach(LOGGER::info);
```
## Class diagram
![alt text](./etc/composite_entity.urm.png "Composite Entity Pattern")
## Applicability
Use the Composite Entity Pattern in the following situation:
* You want to manage multiple dependency objects through one object to adjust the degree of granularity between objects. At the same time, the lifetime of dependency objects depends on a coarse-grained object.
## Credits
* [Composite Entity Pattern in wikipedia](https://en.wikipedia.org/wiki/Composite_entity_pattern)

View File

@ -1,45 +0,0 @@
@startuml
package com.iluwatar.compositeentity {
class App {
+ App(message: String, signal: String)
+ main(args : String[]) {static}
}
class CompositeEntity{
- console : ConsoleCoarseGrainedObject
+ CompositeEntity()
+ setData(message: String, signal: String)
+ getData()
+ init()
}
abstract CoarseGrainedObject{
- dependentObjects : DependentObject[]
+ CoarseGrainedObject()
+ setData(data: T[])
+ getData()
}
abstract DependentObject{
- data : T
+ DependentObject()
+ setData(data: T)
+ getData()
}
class ConsoleCoarseGrainedObject{
+ ConsoleCoarseGrainedObject()
+ getData()
+ init()
}
class MessageDependentObject{
+ MessageDependentObject()
}
class SignalDependentObject{
+ SignalDependentObject()
}
MessageDependentObject --|> DependentObject
SignalDependentObject --|> DependentObject
ConsoleCoarseGrainedObject --|> CoarseGrainedObject
CompositeEntity -right-> ConsoleCoarseGrainedObject
CoarseGrainedObject "1" o--> "0.." DependentObject
App .right.> CompositeEntity
}
@enduml

Binary file not shown.

Before

Width:  |  Height:  |  Size: 90 KiB

View File

@ -1,39 +0,0 @@
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<parent>
<artifactId>java-design-patterns</artifactId>
<groupId>com.iluwatar</groupId>
<version>1.25.0-SNAPSHOT</version>
</parent>
<modelVersion>4.0.0</modelVersion>
<artifactId>composite-entity</artifactId>
<dependencies>
<dependency>
<groupId>org.junit.jupiter</groupId>
<artifactId>junit-jupiter-engine</artifactId>
<scope>test</scope>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-assembly-plugin</artifactId>
<executions>
<execution>
<configuration>
<archive>
<manifest>
<mainClass>com.iluwatar.composite-entity.com.iluwatar.compositeentity.App</mainClass>
</manifest>
</archive>
</configuration>
</execution>
</executions>
</plugin>
</plugins>
</build>
</project>

View File

@ -1,38 +0,0 @@
package com.iluwatar.compositeentity;
import java.util.Arrays;
import lombok.extern.slf4j.Slf4j;
/**
* Composite entity is a Java EE Software design pattern and it is used to model, represent, and
* manage a set of interrelated persistent objects rather than representing them as individual
* fine-grained entity beans, and also a composite entity bean represents a graph of objects.
*/
@Slf4j
public class App {
/**
* An instance that a console manages two related objects.
*/
public App(String message, String signal) {
var console = new CompositeEntity();
console.init();
console.setData(message, signal);
Arrays.stream(console.getData()).forEach(LOGGER::info);
console.setData("Danger", "Red Light");
Arrays.stream(console.getData()).forEach(LOGGER::info);
}
/**
* Program entry point.
*
* @param args command line args
*/
public static void main(String[] args) {
new App("No Danger", "Green Light");
}
}

View File

@ -1,23 +0,0 @@
package com.iluwatar.compositeentity;
import java.util.Arrays;
import java.util.stream.IntStream;
/**
* A coarse-grained object is an object with its own life cycle manages its own relationships to
* other objects. It can be an object contained in the composite entity, or, composite entity itself
* can be the coarse-grained object which holds dependent objects.
*/
public abstract class CoarseGrainedObject<T> {
DependentObject<T>[] dependentObjects;
public void setData(T... data) {
IntStream.range(0, data.length).forEach(i -> dependentObjects[i].setData(data[i]));
}
public T[] getData() {
return (T[]) Arrays.stream(dependentObjects).map(DependentObject::getData).toArray();
}
}

View File

@ -1,23 +0,0 @@
package com.iluwatar.compositeentity;
/**
* Composite entity is the coarse-grained entity bean which may be the coarse-grained object, or may
* contain a reference to the coarse-grained object.
*/
public class CompositeEntity {
private final ConsoleCoarseGrainedObject console = new ConsoleCoarseGrainedObject();
public void setData(String message, String signal) {
console.setData(message, signal);
}
public String[] getData() {
return console.getData();
}
public void init() {
console.init();
}
}

View File

@ -1,20 +0,0 @@
package com.iluwatar.compositeentity;
/**
* A specific CoarseGrainedObject to implement a console.
*/
public class ConsoleCoarseGrainedObject extends CoarseGrainedObject<String> {
@Override
public String[] getData() {
return new String[]{
dependentObjects[0].getData(), dependentObjects[1].getData()
};
}
public void init() {
dependentObjects = new DependentObject[]{
new MessageDependentObject(), new SignalDependentObject()};
}
}

View File

@ -1,20 +0,0 @@
package com.iluwatar.compositeentity;
/**
* It is an object, which can contain other dependent objects (there may be a tree of objects within
* the composite entity), that depends on the coarse-grained object and has its life cycle managed
* by the coarse-grained object.
*/
public abstract class DependentObject<T> {
T data;
public void setData(T message) {
this.data = message;
}
public T getData() {
return data;
}
}

View File

@ -1,9 +0,0 @@
package com.iluwatar.compositeentity;
/**
* The first DependentObject to show message.
*/
public class MessageDependentObject extends DependentObject<String> {
}

View File

@ -1,9 +0,0 @@
package com.iluwatar.compositeentity;
/**
* The second DependentObject to show message.
*/
public class SignalDependentObject extends DependentObject<String> {
}

View File

@ -1,25 +0,0 @@
package com.iluwatar.compositeentity;
import static org.junit.jupiter.api.Assertions.assertDoesNotThrow;
import org.junit.jupiter.api.Test;
/**
* com.iluwatar.compositeentity.App running test
*/
class AppTest {
/**
* Issue: Add at least one assertion to this test case.
* <p>
* Solution: Inserted assertion to check whether the execution of the main method in {@link
* App#main(String[])} throws an exception.
*/
@Test
void shouldExecuteApplicationWithoutException() {
assertDoesNotThrow(() -> App.main(new String[]{}));
}
}

View File

@ -1,32 +0,0 @@
package com.iluwatar.compositeentity;
import org.junit.jupiter.api.Test;
import static org.junit.jupiter.api.Assertions.*;
class PersistenceTest {
final static ConsoleCoarseGrainedObject console = new ConsoleCoarseGrainedObject();
@Test
void dependentObjectChangedForPersistenceTest() {
MessageDependentObject dependentObject = new MessageDependentObject();
console.init();
console.dependentObjects[0] = dependentObject;
String message = "Danger";
assertNull(console.dependentObjects[0].getData());
dependentObject.setData(message);
assertEquals(message, console.dependentObjects[0].getData());
}
@Test
void coarseGrainedObjectChangedForPersistenceTest() {
MessageDependentObject dependentObject = new MessageDependentObject();
console.init();
console.dependentObjects[0] = dependentObject;
String message = "Danger";
assertNull(console.dependentObjects[0].getData());
console.setData(message);
assertEquals(message, dependentObject.getData());
}
}

View File

@ -224,7 +224,6 @@
<module>parameter-object</module>
<module>active-object</module>
<module>model-view-viewmodel</module>
<module>composite-entity</module>
</modules>
<repositories>

View File

@ -1,182 +0,0 @@
---
layout: pattern
title: Abstract Document
folder: abstract-document
permalink: /patterns/abstract-document/
categories: Structural
tags:
- Extensibility
---
## 目的
使用动态属性,并在保持类型安全的同时实现非类型化语言的灵活性。
## 解释
抽象文档模式使您能够处理其他非静态属性。 此模式使用特征的概念来实现类型安全,并将不同类的属性分离为一组接口。
真实世界例子
> 考虑由多个部分组成的汽车。 但是,我们不知道特定汽车是否真的拥有所有零件,或者仅仅是零件中的一部分。 我们的汽车是动态而且非常灵活的。
通俗的说
> 抽象文档模式允许在对象不知道的情况下将属性附加到对象。
维基百科说
> 面向对象的结构设计模式,用于组织松散类型的键值存储中的对象并使用类型化的视图公开数据。 该模式的目的是在强类型语言中实现组件之间的高度灵活性,在这种语言中,可以在不丢失类型安全支持的情况下,将新属性动态地添加到对象树中。 该模式利用特征将类的不同属性分成不同的接口。
**程序示例**
让我们首先定义基类`Document``AbstractDocument`。 它们基本上使对象拥有属性映射和任意数量的子对象。
```java
public interface Document {
Void put(String key, Object value);
Object get(String key);
<T> Stream<T> children(String key, Function<Map<String, Object>, T> constructor);
}
public abstract class AbstractDocument implements Document {
private final Map<String, Object> properties;
protected AbstractDocument(Map<String, Object> properties) {
Objects.requireNonNull(properties, "properties map is required");
this.properties = properties;
}
@Override
public Void put(String key, Object value) {
properties.put(key, value);
return null;
}
@Override
public Object get(String key) {
return properties.get(key);
}
@Override
public <T> Stream<T> children(String key, Function<Map<String, Object>, T> constructor) {
return Stream.ofNullable(get(key))
.filter(Objects::nonNull)
.map(el -> (List<Map<String, Object>>) el)
.findAny()
.stream()
.flatMap(Collection::stream)
.map(constructor);
}
...
}
```
接下来,我们定义一个枚举“属性”和一组类型,价格,模型和零件的接口。 这使我们能够为Car类创建静态外观的界面。
```java
public enum Property {
PARTS, TYPE, PRICE, MODEL
}
public interface HasType extends Document {
default Optional<String> getType() {
return Optional.ofNullable((String) get(Property.TYPE.toString()));
}
}
public interface HasPrice extends Document {
default Optional<Number> getPrice() {
return Optional.ofNullable((Number) get(Property.PRICE.toString()));
}
}
public interface HasModel extends Document {
default Optional<String> getModel() {
return Optional.ofNullable((String) get(Property.MODEL.toString()));
}
}
public interface HasParts extends Document {
default Stream<Part> getParts() {
return children(Property.PARTS.toString(), Part::new);
}
}
```
现在我们准备介绍`Car`
```java
public class Car extends AbstractDocument implements HasModel, HasPrice, HasParts {
public Car(Map<String, Object> properties) {
super(properties);
}
}
```
最后是完整示例中的`Car`构造和使用方式。
```java
LOGGER.info("Constructing parts and car");
var wheelProperties = Map.of(
Property.TYPE.toString(), "wheel",
Property.MODEL.toString(), "15C",
Property.PRICE.toString(), 100L);
var doorProperties = Map.of(
Property.TYPE.toString(), "door",
Property.MODEL.toString(), "Lambo",
Property.PRICE.toString(), 300L);
var carProperties = Map.of(
Property.MODEL.toString(), "300SL",
Property.PRICE.toString(), 10000L,
Property.PARTS.toString(), List.of(wheelProperties, doorProperties));
var car = new Car(carProperties);
LOGGER.info("Here is our car:");
LOGGER.info("-> model: {}", car.getModel().orElseThrow());
LOGGER.info("-> price: {}", car.getPrice().orElseThrow());
LOGGER.info("-> parts: ");
car.getParts().forEach(p -> LOGGER.info("\t{}/{}/{}",
p.getType().orElse(null),
p.getModel().orElse(null),
p.getPrice().orElse(null))
);
// Constructing parts and car
// Here is our car:
// model: 300SL
// price: 10000
// parts:
// wheel/15C/100
// door/Lambo/300
```
## 类图
![alt text](../../abstract-document/etc/abstract-document.png "Abstract Document Traits and Domain")
## 适用性
使用抽象文档模式当
* 需要即时添加新属性
* 你想要一种灵活的方式来以树状结构组织域
* 你想要更宽松的耦合系统
## 鸣谢
* [Wikipedia: Abstract Document Pattern](https://en.wikipedia.org/wiki/Abstract_Document_Pattern)
* [Martin Fowler: Dealing with properties](http://martinfowler.com/apsupp/properties.pdf)
* [Pattern-Oriented Software Architecture Volume 4: A Pattern Language for Distributed Computing (v. 4)](https://www.amazon.com/gp/product/0470059028/ref=as_li_qf_asin_il_tl?ie=UTF8&tag=javadesignpat-20&creative=9325&linkCode=as2&creativeASIN=0470059028&linkId=e3aacaea7017258acf184f9f3283b492)

View File

@ -1,218 +0,0 @@
---
layout: pattern
title: Abstract Factory
folder: abstract-factory
permalink: /patterns/abstract-factory/
categories: Creational
tags:
- Gang of Four
---
## 或称
工具包
## 目的
提供一个用于创建相关对象家族的接口,而无需指定其具体类。
## 解释
真实世界例子
> 要创建一个王国,我们需要具有共同主题的对象。 精灵王国需要精灵王,精灵城堡和精灵军队,而兽人王国需要兽王,精灵城堡和兽人军队。 王国中的对象之间存在依赖性。
通俗的说
> 工厂的工厂; 一个将单个但相关/从属的工厂分组在一起而没有指定其具体类别的工厂。
维基百科上说
> 抽象工厂模式提供了一种封装一组具有共同主题的单个工厂而无需指定其具体类的方法
**程序示例**
翻译上面的王国示例。 首先,我们为王国中的对象提供了一些接口和实现。
```java
public interface Castle {
String getDescription();
}
public interface King {
String getDescription();
}
public interface Army {
String getDescription();
}
// Elven implementations ->
public class ElfCastle implements Castle {
static final String DESCRIPTION = "This is the Elven castle!";
@Override
public String getDescription() {
return DESCRIPTION;
}
}
public class ElfKing implements King {
static final String DESCRIPTION = "This is the Elven king!";
@Override
public String getDescription() {
return DESCRIPTION;
}
}
public class ElfArmy implements Army {
static final String DESCRIPTION = "This is the Elven Army!";
@Override
public String getDescription() {
return DESCRIPTION;
}
}
// Orcish implementations similarly -> ...
```
然后我们有了王国工厂的抽象和实现
```java
public interface KingdomFactory {
Castle createCastle();
King createKing();
Army createArmy();
}
public class ElfKingdomFactory implements KingdomFactory {
public Castle createCastle() {
return new ElfCastle();
}
public King createKing() {
return new ElfKing();
}
public Army createArmy() {
return new ElfArmy();
}
}
public class OrcKingdomFactory implements KingdomFactory {
public Castle createCastle() {
return new OrcCastle();
}
public King createKing() {
return new OrcKing();
}
public Army createArmy() {
return new OrcArmy();
}
}
```
现在我们有了抽象工厂,使我们可以制作相关对象的系列,即精灵王国工厂创建了精灵城堡,国王和军队等。
```java
var factory = new ElfKingdomFactory();
var castle = factory.createCastle();
var king = factory.createKing();
var army = factory.createArmy();
castle.getDescription();
king.getDescription();
army.getDescription();
```
程序输出:
```java
This is the Elven castle!
This is the Elven king!
This is the Elven Army!
```
现在,我们可以为不同的王国工厂设计工厂。 在此示例中我们创建了FactoryMaker负责返回ElfKingdomFactory或OrcKingdomFactory的实例。 客户可以使用FactoryMaker来创建所需的具体工厂该工厂随后将生产不同的具体对象军队国王城堡。 在此示例中,我们还使用了一个枚举来参数化客户要求的王国工厂类型。
```java
public static class FactoryMaker {
public enum KingdomType {
ELF, ORC
}
public static KingdomFactory makeFactory(KingdomType type) {
switch (type) {
case ELF:
return new ElfKingdomFactory();
case ORC:
return new OrcKingdomFactory();
default:
throw new IllegalArgumentException("KingdomType not supported.");
}
}
}
public static void main(String[] args) {
var app = new App();
LOGGER.info("Elf Kingdom");
app.createKingdom(FactoryMaker.makeFactory(KingdomType.ELF));
LOGGER.info(app.getArmy().getDescription());
LOGGER.info(app.getCastle().getDescription());
LOGGER.info(app.getKing().getDescription());
LOGGER.info("Orc Kingdom");
app.createKingdom(FactoryMaker.makeFactory(KingdomType.ORC));
-- similar use of the orc factory
}
```
## 类图
![alt text](../../abstract-factory/etc/abstract-factory.urm.png "Abstract Factory class diagram")
## 适用性
在以下情况下使用抽象工厂模式
* 该系统应独立于其产品的创建,组成和表示方式
* 系统应配置有多个产品系列之一
* 相关产品对象系列旨在一起使用,你需要强制执行此约束
* 你想提供产品的类库,并且只想暴露它们的接口,而不是它们的实现。
* 从概念上讲,依赖项的生存期比使用者的生存期短。
* 你需要一个运行时值来构建特定的依赖关系
* 你想决定在运行时从系列中调用哪种产品。
* 你需要提供一个或更多仅在运行时才知道的参数,然后才能解决依赖关系。
* 当你需要产品之间的一致性时
* 在向程序添加新产品或产品系列时,您不想更改现有代码。
示例场景
* 在运行时在FileSystemAcmeService DatabaseAcmeService 或NetworkAcmeService中选择并调用一个
* 单元测试用例的编写变得更加容易
* 适用于不同操作系统的UI工具
## 后果:
* Java中的依赖注入会隐藏服务类的依赖关系这些依赖关系可能导致运行时错误而这些错误在编译时会被捕获。
* 虽然在创建预定义对象时模式很好,但是添加新对象可能会很困难。
* 由于引入了许多新的接口和类,因此代码变得比应有的复杂。
## 教程
* [Abstract Factory Pattern Tutorial](https://www.journaldev.com/1418/abstract-factory-design-pattern-in-java)
## 已知使用
* [javax.xml.parsers.DocumentBuilderFactory](http://docs.oracle.com/javase/8/docs/api/javax/xml/parsers/DocumentBuilderFactory.html)
* [javax.xml.transform.TransformerFactory](http://docs.oracle.com/javase/8/docs/api/javax/xml/transform/TransformerFactory.html#newInstance--)
* [javax.xml.xpath.XPathFactory](http://docs.oracle.com/javase/8/docs/api/javax/xml/xpath/XPathFactory.html#newInstance--)
## 相关模式
* [Factory Method](https://java-design-patterns.com/patterns/factory-method/)
* [Factory Kit](https://java-design-patterns.com/patterns/factory-kit/)
## 鸣谢
* [Design Patterns: Elements of Reusable Object-Oriented Software](https://www.amazon.com/gp/product/0201633612/ref=as_li_tl?ie=UTF8&camp=1789&creative=9325&creativeASIN=0201633612&linkCode=as2&tag=javadesignpat-20&linkId=675d49790ce11db99d90bde47f1aeb59)
* [Head First Design Patterns: A Brain-Friendly Guide](https://www.amazon.com/gp/product/0596007124/ref=as_li_tl?ie=UTF8&camp=1789&creative=9325&creativeASIN=0596007124&linkCode=as2&tag=javadesignpat-20&linkId=6b8b6eea86021af6c8e3cd3fc382cb5b)

View File

@ -1,124 +0,0 @@
---
layout: pattern
title: Active Object
folder: active-object
permalink: /patterns/active-object/
categories: Concurrency
tags:
- Performance
---
## 目的
活动对象设计模式使每个驻留在其控制线程中的对象的方法执行与方法调用脱钩。 目的是通过使用异步方法调用和用于处理请求的调度程序来引入并发。
## 解释
实现活动对象模式的类将包含自同步机制,而无需使用“同步”方法。
真实世界例子
>兽人以其野性和顽强的灵魂而著称。 似乎他们有基于先前行为的控制线程。
要实现具有自己的控制机制线程并仅公开其API而不公开自己的执行我们可以使用活动对象模式。
**程序示例**
```java
public abstract class ActiveCreature{
private final Logger logger = LoggerFactory.getLogger(ActiveCreature.class.getName());
private BlockingQueue<Runnable> requests;
private String name;
private Thread thread;
public ActiveCreature(String name) {
this.name = name;
this.requests = new LinkedBlockingQueue<Runnable>();
thread = new Thread(new Runnable() {
@Override
public void run() {
while (true) {
try {
requests.take().run();
} catch (InterruptedException e) {
logger.error(e.getMessage());
}
}
}
}
);
thread.start();
}
public void eat() throws InterruptedException {
requests.put(new Runnable() {
@Override
public void run() {
logger.info("{} is eating!",name());
logger.info("{} has finished eating!",name());
}
}
);
}
public void roam() throws InterruptedException {
requests.put(new Runnable() {
@Override
public void run() {
logger.info("{} has started to roam and the wastelands.",name());
}
}
);
}
public String name() {
return this.name;
}
}
```
我们可以看到任何将扩展ActiveCreature的类都将具有自己的控制线程来执行和调用方法。
例如,兽人类:
```java
public class Orc extends ActiveCreature {
public Orc(String name) {
super(name);
}
}
```
现在,我们可以创建多个生物,例如兽人,告诉他们吃东西和散步,然后他们将在自己的控制线程上执行它:
```java
public static void main(String[] args) {
var app = new App();
app.run();
}
@Override
public void run() {
ActiveCreature creature;
try {
for (int i = 0;i < creatures;i++) {
creature = new Orc(Orc.class.getSimpleName().toString() + i);
creature.eat();
creature.roam();
}
Thread.sleep(1000);
} catch (InterruptedException e) {
logger.error(e.getMessage());
}
Runtime.getRuntime().exit(1);
}
```
## 类图
![alt text](../../active-object/etc/active-object.urm.PNG "Active Object class diagram")

View File

@ -1,157 +0,0 @@
---
layout: pattern
title: Acyclic Visitor
folder: acyclic-visitor
permalink: /patterns/acyclic-visitor/
categories: Behavioral
tags:
- Extensibility
---
## 目的
允许将新功能添加到现有的类层次结构中,而不会影响这些层次结构,也不会有四人帮访客模式中那样循环依赖的问题。
## 解释
真实世界例子
> 我们有一个调制解调器类的层次结构。 需要使用基于过滤条件的外部算法是Unix或DOS兼容的调制解调器来访问此层次结构中的调制解调器。
通俗地说
> 非循环访问者允许将功能添加到现有的类层次结构中,而无需修改层次结构
[WikiWikiWeb](https://wiki.c2.com/?AcyclicVisitor) 上说
> 非循环访客模式允许将新功能添加到现有的类层次结构中,而不会影响这些层次结构,也不会创建四人帮访客模式中固有的循环依赖问题。
**程序示例**
这是调制解调器的层次结构。
```java
public abstract class Modem {
public abstract void accept(ModemVisitor modemVisitor);
}
public class Zoom extends Modem {
...
@Override
public void accept(ModemVisitor modemVisitor) {
if (modemVisitor instanceof ZoomVisitor) {
((ZoomVisitor) modemVisitor).visit(this);
} else {
LOGGER.info("Only ZoomVisitor is allowed to visit Zoom modem");
}
}
}
public class Hayes extends Modem {
...
@Override
public void accept(ModemVisitor modemVisitor) {
if (modemVisitor instanceof HayesVisitor) {
((HayesVisitor) modemVisitor).visit(this);
} else {
LOGGER.info("Only HayesVisitor is allowed to visit Hayes modem");
}
}
}
```
下面我们介绍`调制解调器访问者`类结构。
```java
public interface ModemVisitor {
}
public interface HayesVisitor extends ModemVisitor {
void visit(Hayes hayes);
}
public interface ZoomVisitor extends ModemVisitor {
void visit(Zoom zoom);
}
public interface AllModemVisitor extends ZoomVisitor, HayesVisitor {
}
public class ConfigureForDosVisitor implements AllModemVisitor {
...
@Override
public void visit(Hayes hayes) {
LOGGER.info(hayes + " used with Dos configurator.");
}
@Override
public void visit(Zoom zoom) {
LOGGER.info(zoom + " used with Dos configurator.");
}
}
public class ConfigureForUnixVisitor implements ZoomVisitor {
...
@Override
public void visit(Zoom zoom) {
LOGGER.info(zoom + " used with Unix configurator.");
}
}
```
最后,这里是访问者的实践。
```java
var conUnix = new ConfigureForUnixVisitor();
var conDos = new ConfigureForDosVisitor();
var zoom = new Zoom();
var hayes = new Hayes();
hayes.accept(conDos);
zoom.accept(conDos);
hayes.accept(conUnix);
zoom.accept(conUnix);
```
程序输出:
```
// Hayes modem used with Dos configurator.
// Zoom modem used with Dos configurator.
// Only HayesVisitor is allowed to visit Hayes modem
// Zoom modem used with Unix configurator.
```
## 类图
![alt text](../../acyclic-visitor/etc/acyclic-visitor.png "Acyclic Visitor")
## 适用性
以下情况可以使用此模式:
* 需要在现有层次结构中添加新功能而无需更改或影响该层次结构时。
* 当某些功能在层次结构上运行,但不属于层次结构本身时。 例如 ConfigureForDOS / ConfigureForUnix / ConfigureForX问题。
* 当您需要根据对象的类型对对象执行非常不同的操作时。
* 当访问的类层次结构将经常使用元素类的新派生进行扩展时。
* 当重新编译,重新链接,重新测试或重新分发派生元素非常昂贵时。
## 结果
好处:
* 类层次结构之间没有依赖关系循环。
* 如果添加了新访客,则无需重新编译所有访客。
* 如果类层次结构具有新成员,则不会导致现有访问者中的编译失败。
坏处:
* 通过证明它可以接受所有访客,但实际上仅对特定访客感兴趣,从而违反了[Liskov的替代原则](https://java-design-patterns.com/principles/#liskov-substitution-principle)
* 必须为可访问的类层次结构中的所有成员创建访问者的并行层次结构。
## 相关的模式
* [Visitor Pattern](https://java-design-patterns.com/patterns/visitor/)
## 鸣谢
* [Acyclic Visitor by Robert C. Martin](http://condor.depaul.edu/dmumaugh/OOT/Design-Principles/acv.pdf)
* [Acyclic Visitor in WikiWikiWeb](https://wiki.c2.com/?AcyclicVisitor)

View File

@ -1,107 +0,0 @@
---
layout: pattern
title: Aggregator Microservices
folder: aggregator-microservices
permalink: /patterns/aggregator-microservices/
categories: Architectural
tags:
- Cloud distributed
- Decoupling
- Microservices
---
## 意图
用户对聚合器服务进行一次调用,然后聚合器将调用每个相关的微服务。
## 解释
真实世界例子
> 我们的网络市场需要有关产品及其当前库存的信息。 它调用聚合服务,聚合服务依次调用产品信息微服务和产品库存微服务,返回组合信息。
通俗地说
> 聚合器微服务从各种微服务中收集数据,并返回一个聚合数据以进行处理。
Stack Overflow上说
> 聚合器微服务调用多个服务以实现应用程序所需的功能。
**程序示例**
让我们从数据模型开始。 这是我们的`产品`
```java
public class Product {
private String title;
private int productInventories;
// getters and setters ->
...
}
```
接下来,我们将介绍我们的聚合器微服务。 它包含用于调用相应微服务的客户端`ProductInformationClient`` ProductInventoryClient`
```java
@RestController
public class Aggregator {
@Resource
private ProductInformationClient informationClient;
@Resource
private ProductInventoryClient inventoryClient;
@RequestMapping(path = "/product", method = RequestMethod.GET)
public Product getProduct() {
var product = new Product();
var productTitle = informationClient.getProductTitle();
var productInventory = inventoryClient.getProductInventories();
//Fallback to error message
product.setTitle(requireNonNullElse(productTitle, "Error: Fetching Product Title Failed"));
//Fallback to default error inventory
product.setProductInventories(requireNonNullElse(productInventory, -1));
return product;
}
}
```
这是产品信息微服务的精华实现。 库存微服务类似,它只返回库存计数。
```java
@RestController
public class InformationController {
@RequestMapping(value = "/information", method = RequestMethod.GET)
public String getProductTitle() {
return "The Product Title.";
}
}
```
Now calling our `Aggregator` REST API returns the product information.
现在调用我们的聚合器 REST API会返回产品信息。
```bash
curl http://localhost:50004/product
{"title":"The Product Title.","productInventories":5}
```
## 类图
![alt text](../../aggregator-microservices/aggregator-service/etc/aggregator-service.png "Aggregator Microservice")
## 适用性
当需要各种微服务的统一API时无论客户端设备如何都可以使用Aggregator微服务模式。
## 鸣谢
* [Microservice Design Patterns](http://web.archive.org/web/20190705163602/http://blog.arungupta.me/microservice-design-patterns/)
* [Microservices Patterns: With examples in Java](https://www.amazon.com/gp/product/1617294543/ref=as_li_qf_asin_il_tl?ie=UTF8&tag=javadesignpat-20&creative=9325&linkCode=as2&creativeASIN=1617294543&linkId=8b4e570267bc5fb8b8189917b461dc60)
* [Architectural Patterns: Uncover essential patterns in the most indispensable realm of enterprise architecture](https://www.amazon.com/gp/product/B077T7V8RC/ref=as_li_qf_asin_il_tl?ie=UTF8&tag=javadesignpat-20&creative=9325&linkCode=as2&creativeASIN=B077T7V8RC&linkId=c34d204bfe1b277914b420189f09c1a4)

View File

@ -1,196 +0,0 @@
---
layout: pattern
title: Ambassador
folder: ambassador
permalink: /patterns/ambassador/
categories: Structural
tags:
- Decoupling
- Cloud distributed
---
## 目的
在客户端上提供帮助程序服务实例,并从共享资源上转移常用功能。
## 解释
真实世界例子
> 远程服务有许多客户端访问它提供的功能。 该服务是旧版应用程序,无法更新。 用户的大量请求导致连接问题。新的请求频率规则需要同时实现延迟检测和客户端日志功能。
通俗的说
> 使用“大使”模式,我们可以实现来自客户端的频率较低的轮询以及延迟检查和日志记录。
微软文档做了如下阐述
> 可以将大使服务视为与客户端位于同一位置的进程外代理。 此模式对于以语言不可知的方式减轻常见的客户端连接任务例如监视日志记录路由安全性如TLS和弹性模式的工作很有用。 它通常与旧版应用程序或其他难以修改的应用程序一起使用,以扩展其网络功能。 它还可以使专业团队实现这些功能。
**程序示例**
有了上面的介绍我们将在这个例子中模仿功能。我们有一个用远程服务实现的接口,同时也是大使服务。
```java
interface RemoteServiceInterface {
long doRemoteFunction(int value) throws Exception;
}
```
表示为单例的远程服务。
```java
public class RemoteService implements RemoteServiceInterface {
private static final Logger LOGGER = LoggerFactory.getLogger(RemoteService.class);
private static RemoteService service = null;
static synchronized RemoteService getRemoteService() {
if (service == null) {
service = new RemoteService();
}
return service;
}
private RemoteService() {}
@Override
public long doRemoteFunction(int value) {
long waitTime = (long) Math.floor(Math.random() * 1000);
try {
sleep(waitTime);
} catch (InterruptedException e) {
LOGGER.error("Thread sleep interrupted", e);
}
return waitTime >= 200 ? value * 10 : -1;
}
}
```
服务大使添加了像日志和延迟检测的额外功能
```java
public class ServiceAmbassador implements RemoteServiceInterface {
private static final Logger LOGGER = LoggerFactory.getLogger(ServiceAmbassador.class);
private static final int RETRIES = 3;
private static final int DELAY_MS = 3000;
ServiceAmbassador() {
}
@Override
public long doRemoteFunction(int value) {
return safeCall(value);
}
private long checkLatency(int value) {
var startTime = System.currentTimeMillis();
var result = RemoteService.getRemoteService().doRemoteFunction(value);
var timeTaken = System.currentTimeMillis() - startTime;
LOGGER.info("Time taken (ms): " + timeTaken);
return result;
}
private long safeCall(int value) {
var retries = 0;
var result = (long) FAILURE;
for (int i = 0; i < RETRIES; i++) {
if (retries >= RETRIES) {
return FAILURE;
}
if ((result = checkLatency(value)) == FAILURE) {
LOGGER.info("Failed to reach remote: (" + (i + 1) + ")");
retries++;
try {
sleep(DELAY_MS);
} catch (InterruptedException e) {
LOGGER.error("Thread sleep state interrupted", e);
}
} else {
break;
}
}
return result;
}
}
```
客户端具有用于与远程服务进行交互的本地服务大使:
```java
public class Client {
private static final Logger LOGGER = LoggerFactory.getLogger(Client.class);
private final ServiceAmbassador serviceAmbassador = new ServiceAmbassador();
long useService(int value) {
var result = serviceAmbassador.doRemoteFunction(value);
LOGGER.info("Service result: " + result);
return result;
}
}
```
这是两个使用该服务的客户端。
```java
public class App {
public static void main(String[] args) {
var host1 = new Client();
var host2 = new Client();
host1.useService(12);
host2.useService(73);
}
}
```
Here's the output for running the example:
```java
Time taken (ms): 111
Service result: 120
Time taken (ms): 931
Failed to reach remote: (1)
Time taken (ms): 665
Failed to reach remote: (2)
Time taken (ms): 538
Failed to reach remote: (3)
Service result: -1
```
## 类图
![alt text](../../ambassador/etc/ambassador.urm.png "Ambassador class diagram")
## 适用性
大使适用于无法修改或极难修改的旧式远程服务。 可以在客户端上实现连接性的功能,而无需更改远程服务。
* 大使提供了用于远程服务的本地接口。
* 大使在客户端上提供日志记录,断路,重试和安全性。
## 典型用例
* 控制对另一个对象的访问
* 实现日志
* 卸载远程服务任务
* 简化网络连接
## 已知使用
* [Kubernetes-native API gateway for microservices](https://github.com/datawire/ambassador)
## 相关模式
* [Proxy](https://java-design-patterns.com/patterns/proxy/)
## 鸣谢
* [Ambassador pattern](https://docs.microsoft.com/en-us/azure/architecture/patterns/ambassador)
* [Designing Distributed Systems: Patterns and Paradigms for Scalable, Reliable Services](https://books.google.co.uk/books?id=6BJNDwAAQBAJ&pg=PT35&lpg=PT35&dq=ambassador+pattern+in+real+world&source=bl&ots=d2e7GhYdHi&sig=Lfl_MDnCgn6lUcjzOg4GXrN13bQ&hl=en&sa=X&ved=0ahUKEwjk9L_18rrbAhVpKcAKHX_KA7EQ6AEIWTAI#v=onepage&q=ambassador%20pattern%20in%20real%20world&f=false)

View File

@ -1,138 +0,0 @@
---
layout: pattern
title: API Gateway
folder: api-gateway
permalink: /patterns/api-gateway/
categories: Architectural
tags:
- Cloud distributed
- Decoupling
- Microservices
---
## 目的
API网关将所有对微服务的调用聚合到一起。用户对API网关进行一次调用然后API网关调用每个相关的微服务。
## 解释
使用微服务模式,客户端可能需要来自多个不同微服务的数据。 如果客户端直接调用每个微服务,则可能会导致更长的加载时间,因为客户端将不得不为每个调用的微服务发出网络请求。此外,让客户端调用每个微服务会直接将客户端与该微服务相关联-如果微服务的内部实现发生了变化(例如,如果将来某个时候合并了两个微服务),或者微服务的位置(主机和端口) 更改,则必须更新使用这些微服务的每个客户端。
API网关模式的目的是缓解其中的一些问题。 在API网关模式中在客户端和微服务之间放置了一个附加实体API网关。API网关的工作是将对微服务的调用进行聚合。 客户端不是一次单独调用每个微服务而是一次调用API网关。 然后API网关调用客户端所需的每个微服务。
真实世界例子
> 我们正在为电子商务站点实现微服务和API网关模式。 在此系统中API网关调用Image和Price微服务。
通俗地说
> 对于使用微服务架构实现的系统API是聚合微服务调用的入口点。
维基百科说
> API网关是充当API前置接收API请求执行限制和安全策略将请求传递到后端服务然后将响应传递回请求者的服务器。网关通常包括一个转换引擎以实时地编排和修改请求和响应。 网关可以提供收集分析数据和提供缓存等功能。网关还可以提供支持身份验证,授权,安全性,审计和法规遵从性的功能。
**程序示例**
此实现展示了电子商务站点的API网关模式。` ApiGateway`分别使用` ImageClientImpl`` PriceClientImpl`来调用Image和Price微服务。 在桌面设备上查看该网站的客户可以看到价格信息和产品图片,因此` ApiGateway`会调用这两种微服务并在`DesktopProduct`模型中汇总数据。 但是,移动用户只能看到价格信息。 他们看不到产品图片。 对于移动用户,`ApiGateway`仅检索价格信息,并将其用于填充`MobileProduct`模型。
这个是图像微服务的实现。
```java
public interface ImageClient {
String getImagePath();
}
public class ImageClientImpl implements ImageClient {
@Override
public String getImagePath() {
var httpClient = HttpClient.newHttpClient();
var httpGet = HttpRequest.newBuilder()
.GET()
.uri(URI.create("http://localhost:50005/image-path"))
.build();
try {
var httpResponse = httpClient.send(httpGet, BodyHandlers.ofString());
return httpResponse.body();
} catch (IOException | InterruptedException e) {
e.printStackTrace();
}
return null;
}
}
```
这里是价格服务的实现。
```java
public interface PriceClient {
String getPrice();
}
public class PriceClientImpl implements PriceClient {
@Override
public String getPrice() {
var httpClient = HttpClient.newHttpClient();
var httpGet = HttpRequest.newBuilder()
.GET()
.uri(URI.create("http://localhost:50006/price"))
.build();
try {
var httpResponse = httpClient.send(httpGet, BodyHandlers.ofString());
return httpResponse.body();
} catch (IOException | InterruptedException e) {
e.printStackTrace();
}
return null;
}
}
```
在这里我们可以看到API网关如何将请求映射到微服务。
```java
public class ApiGateway {
@Resource
private ImageClient imageClient;
@Resource
private PriceClient priceClient;
@RequestMapping(path = "/desktop", method = RequestMethod.GET)
public DesktopProduct getProductDesktop() {
var desktopProduct = new DesktopProduct();
desktopProduct.setImagePath(imageClient.getImagePath());
desktopProduct.setPrice(priceClient.getPrice());
return desktopProduct;
}
@RequestMapping(path = "/mobile", method = RequestMethod.GET)
public MobileProduct getProductMobile() {
var mobileProduct = new MobileProduct();
mobileProduct.setPrice(priceClient.getPrice());
return mobileProduct;
}
}
```
## 类图
![alt text](../../api-gateway/etc/api-gateway.png "API Gateway")
## 适用性
在以下情况下使用API网关模式
* 你正在使用微服务架构,并且需要聚合单点来进行微服务调用。
## 鸣谢
* [microservices.io - API Gateway](http://microservices.io/patterns/apigateway.html)
* [NGINX - Building Microservices: Using an API Gateway](https://www.nginx.com/blog/building-microservices-using-an-api-gateway/)
* [Microservices Patterns: With examples in Java](https://www.amazon.com/gp/product/1617294543/ref=as_li_qf_asin_il_tl?ie=UTF8&tag=javadesignpat-20&creative=9325&linkCode=as2&creativeASIN=1617294543&linkId=ac7b6a57f866ac006a309d9086e8cfbd)
* [Building Microservices: Designing Fine-Grained Systems](https://www.amazon.com/gp/product/1491950358/ref=as_li_qf_asin_il_tl?ie=UTF8&tag=javadesignpat-20&creative=9325&linkCode=as2&creativeASIN=1491950358&linkId=4c95ca9831e05e3f0dadb08841d77bf1)

View File

@ -1,143 +0,0 @@
---
layout: pattern
title: Arrange/Act/Assert
folder: arrange-act-assert
permalink: /patterns/arrange-act-assert/
categories: Idiom
tags:
- Testing
---
## 或称
Given/When/Then
## 意图
安排/执行/断言AAA是组织单元测试的一种模式。
它将测试分为三个清晰而独特的步骤:
1. 安排:执行测试所需的设置和初始化。
2. 执行:采取测试所需的行动。
3. 断言:验证测试结果。
## 解释
这种模式有几个明显的好处。 它在测试的设置,操作和结果之间建立了清晰的分隔。 这种结构使代码更易于阅读和理解。 如果按顺序排列步骤并格式化代码以将它们分开,则可以扫描测试并快速了解其功能。
当您编写测试时,它还会强制执行一定程度的纪律。 您必须清楚地考虑您的测试将执行的三个步骤。 由于您已经有了大纲,因此可以使同时编写测试变得更加自然。
真实世界例子
> 我们需要为一个类编写全面而清晰的单元测试套件。
通俗地说
> 安排/执行/断言是一种测试模式,将测试分为三个清晰的步骤以方便维护。
WikiWikiWeb 上说
> 安排/执行/断言是用于在单元测试方法中排列和格式化代码的模式。
**程序示例**
让我们首先介绍要进行单元测试的`Cash`类。
```java
public class Cash {
private int amount;
Cash(int amount) {
this.amount = amount;
}
void plus(int addend) {
amount += addend;
}
boolean minus(int subtrahend) {
if (amount >= subtrahend) {
amount -= subtrahend;
return true;
} else {
return false;
}
}
int count() {
return amount;
}
}
```
Then we write our unit tests according to Arrange/Act/Assert pattern. Notice the clearly
separated steps for each unit test.
然后我们根据Arrange / Act / Assert模式编写单元测试。 注意每个单元测试的步骤是分开的清晰的。
```java
class CashAAATest {
@Test
void testPlus() {
//Arrange
var cash = new Cash(3);
//Act
cash.plus(4);
//Assert
assertEquals(7, cash.count());
}
@Test
void testMinus() {
//Arrange
var cash = new Cash(8);
//Act
var result = cash.minus(5);
//Assert
assertTrue(result);
assertEquals(3, cash.count());
}
@Test
void testInsufficientMinus() {
//Arrange
var cash = new Cash(1);
//Act
var result = cash.minus(6);
//Assert
assertFalse(result);
assertEquals(1, cash.count());
}
@Test
void testUpdate() {
//Arrange
var cash = new Cash(5);
//Act
cash.plus(6);
var result = cash.minus(3);
//Assert
assertTrue(result);
assertEquals(8, cash.count());
}
}
```
## 适用性
使用 Arrange/Act/Assert 模式当
* You need to structure your unit tests so that they're easier to read, maintain, and enhance.
* 你需要结构化你的单元测试代码这样它们可以更好的阅读,维护和增强。
## 鸣谢
* [Arrange, Act, Assert: What is AAA Testing?](https://blog.ncrunch.net/post/arrange-act-assert-aaa-testing.aspx)
* [Bill Wake: 3A Arrange, Act, Assert](https://xp123.com/articles/3a-arrange-act-assert/)
* [Martin Fowler: GivenWhenThen](https://martinfowler.com/bliki/GivenWhenThen.html)
* [xUnit Test Patterns: Refactoring Test Code](https://www.amazon.com/gp/product/0131495054/ref=as_li_qf_asin_il_tl?ie=UTF8&tag=javadesignpat-20&creative=9325&linkCode=as2&creativeASIN=0131495054&linkId=99701e8f4af2f7e8dd50d720c9b63dbf)
* [Unit Testing Principles, Practices, and Patterns](https://www.amazon.com/gp/product/1617296279/ref=as_li_qf_asin_il_tl?ie=UTF8&tag=javadesignpat-20&creative=9325&linkCode=as2&creativeASIN=1617296279&linkId=74c75cf22a63c3e4758ae08aa0a0cc35)
* [Test Driven Development: By Example](https://www.amazon.com/gp/product/0321146530/ref=as_li_qf_asin_il_tl?ie=UTF8&tag=javadesignpat-20&creative=9325&linkCode=as2&creativeASIN=0321146530&linkId=5c63a93d8c1175b84ca5087472ef0e05)

View File

@ -1,163 +0,0 @@
---
layout: pattern
title: Version Number
folder: versionnumber
permalink: /patterns/versionnumber/
description: Entity versioning with version number
categories:
- Concurrency
tags:
- Data access
- Microservices
---
## 名字 / 分类
版本号
## 或称
实体版本控制,乐观锁。
## 目的
解决多个客户端尝试同时更新同一实体时的并发冲突。
## 解释
现实世界的例子
> 爱丽丝Alice和鲍勃Bob正在管理书该书存储在数据库中。 我们的英雄们正在同时进行更改,我们需要某种机制来防止他们相互覆盖。
通俗地说
> 版本号模式可防止对同一实体进行并发更新。
维基百科说
> 乐观并发控制假设多个事务可以频繁完成而不会互相干扰。 在运行时,事务使用数据资源而不获取这些资源的锁。 在提交之前,每个事务都将验证没有其他事务修改了已读取的数据。如果检查发现有冲突的修改,则提交的事务将回滚并可以重新启动。
**程序示例**
我们有`Book` 已版本化的实体,它有一个复制构造函数。
```java
public class Book {
private long id;
private String title = "";
private String author = "";
private long version = 0; // version number
public Book(Book book) {
this.id = book.id;
this.title = book.title;
this.author = book.author;
this.version = book.version;
}
// getters and setters are omitted here
}
```
我们还有一个 `BookRepository`, 它实现了并发控制。
```java
public class BookRepository {
private final Map<Long, Book> collection = new HashMap<>();
public void update(Book book) throws BookNotFoundException, VersionMismatchException {
if (!collection.containsKey(book.getId())) {
throw new BookNotFoundException("Not found book with id: " + book.getId());
}
var latestBook = collection.get(book.getId());
if (book.getVersion() != latestBook.getVersion()) {
throw new VersionMismatchException(
"Tried to update stale version " + book.getVersion()
+ " while actual version is " + latestBook.getVersion()
);
}
// update version, including client representation - modify by reference here
book.setVersion(book.getVersion() + 1);
// save book copy to repository
collection.put(book.getId(), new Book(book));
}
public Book get(long bookId) throws BookNotFoundException {
if (!collection.containsKey(bookId)) {
throw new BookNotFoundException("Not found book with id: " + bookId);
}
// return copy of the book
return new Book(collection.get(bookId));
}
}
```
这是实践中的并发控制:
```java
var bookId = 1;
// Alice and Bob took the book concurrently
final var aliceBook = bookRepository.get(bookId);
final var bobBook = bookRepository.get(bookId);
aliceBook.setTitle("Kama Sutra"); // Alice has updated book title
bookRepository.update(aliceBook); // and successfully saved book in database
LOGGER.info("Alice updates the book with new version {}", aliceBook.getVersion());
// now Bob has the stale version of the book with empty title and version = 0
// while actual book in database has filled title and version = 1
bobBook.setAuthor("Vatsyayana Mallanaga"); // Bob updates the author
try {
LOGGER.info("Bob tries to update the book with his version {}", bobBook.getVersion());
bookRepository.update(bobBook); // Bob tries to save his book to database
} catch (VersionMismatchException e) {
// Bob update fails, and book in repository remained untouchable
LOGGER.info("Exception: {}", e.getMessage());
// Now Bob should reread actual book from repository, do his changes again and save again
}
```
程序输出:
```java
Alice updates the book with new version 1
Bob tries to update the book with his version 0
Exception: Tried to update stale version 0 while actual version is 1
```
## 类图
![alt text](../../version-number/etc/version-number.urm.png "Version Number pattern class diagram")
## 适用性
将版本号用于:
* 解决对数据的并发写访问
* 强的数据一致性
## 教程
* [Version Number Pattern Tutorial](http://www.java2s.com/Tutorial/Java/0355__JPA/VersioningEntity.htm)
## 已知用途
* [Hibernate](https://vladmihalcea.com/jpa-entity-version-property-hibernate/)
* [Elasticsearch](https://www.elastic.co/guide/en/elasticsearch/reference/current/docs-index_.html#index-versioning)
* [Apache Solr](https://lucene.apache.org/solr/guide/6_6/updating-parts-of-documents.html)
## 意义
版本号模式允许实现并发控制,通常通过乐观离线锁模式来完成。
## 相关模式
* [Optimistic Offline Lock](https://martinfowler.com/eaaCatalog/optimisticOfflineLock.html)
## 鸣谢
* [Optimistic Locking in JPA](https://www.baeldung.com/jpa-optimistic-locking)
* [JPA entity versioning](https://www.byteslounge.com/tutorials/jpa-entity-versioning-version-and-optimistic-locking)
* [J2EE Design Patterns](http://ommolketab.ir/aaf-lib/axkwht7wxrhvgs2aqkxse8hihyu9zv.pdf)