Compare commits
2 Commits
all-contri
...
all-contri
Author | SHA1 | Date | |
---|---|---|---|
bea39206ed | |||
c3228fd6d2 |
@ -1460,25 +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"
|
||||
]
|
||||
},
|
||||
{
|
||||
"login": "Al-assad",
|
||||
"name": "余林颖",
|
||||
"avatar_url": "https://avatars.githubusercontent.com/u/22493821?v=4",
|
||||
"profile": "https://al-assad.github.io/notion/",
|
||||
"contributions": [
|
||||
"translation",
|
||||
"projectManagement"
|
||||
]
|
||||
}
|
||||
],
|
||||
"contributorsPerLine": 4,
|
||||
|
@ -10,7 +10,7 @@
|
||||
[](https://sonarcloud.io/dashboard?id=iluwatar_java-design-patterns)
|
||||
[](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 -->
|
||||
[](#contributors-)
|
||||
[](#contributors-)
|
||||
<!-- ALL-CONTRIBUTORS-BADGE:END -->
|
||||
|
||||
<br/>
|
||||
@ -315,10 +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>
|
||||
<td align="center"><a href="https://al-assad.github.io/notion/"><img src="https://avatars.githubusercontent.com/u/22493821?v=4?s=100" width="100px;" alt=""/><br /><sub><b>余林颖</b></sub></a><br /><a href="#translation-Al-assad" title="Translation">🌍</a> <a href="#projectManagement-Al-assad" title="Project Management">📆</a></td>
|
||||
</tr>
|
||||
</table>
|
||||
|
||||
<!-- markdownlint-restore -->
|
||||
|
@ -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
|
||||
|
||||

|
||||
|
||||
## 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)
|
@ -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 |
@ -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>
|
@ -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");
|
||||
|
||||
}
|
||||
}
|
@ -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();
|
||||
}
|
||||
}
|
@ -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();
|
||||
}
|
||||
}
|
@ -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()};
|
||||
}
|
||||
}
|
@ -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;
|
||||
}
|
||||
}
|
@ -1,9 +0,0 @@
|
||||
package com.iluwatar.compositeentity;
|
||||
|
||||
/**
|
||||
* The first DependentObject to show message.
|
||||
*/
|
||||
|
||||
public class MessageDependentObject extends DependentObject<String> {
|
||||
|
||||
}
|
@ -1,9 +0,0 @@
|
||||
package com.iluwatar.compositeentity;
|
||||
|
||||
/**
|
||||
* The second DependentObject to show message.
|
||||
*/
|
||||
|
||||
public class SignalDependentObject extends DependentObject<String> {
|
||||
|
||||
}
|
@ -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[]{}));
|
||||
|
||||
}
|
||||
}
|
@ -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());
|
||||
}
|
||||
}
|
26
ko/README.md
26
ko/README.md
@ -14,35 +14,35 @@
|
||||
|
||||
# 소개
|
||||
|
||||
디자인 패턴은 개발자가 응용 프로그램이나 시스템을 디자인할 때 일반적인 문제를 해결하는 데 사용할 수 있는 가장 정석적인 방법입니다.
|
||||
디자인 패턴은 프로그래머가 응용 프로그램이나 시스템을 디자인 할 때 일반적인 문제를 해결하는 데 사용할 수있는 가장 공식화 된 방법입니다.
|
||||
|
||||
디자인 패턴은 테스트되고 입증된 개발 패러다임을 제공하여 개발 프로세스 속도를 높일 수 있습니다.
|
||||
디자인 패턴은 테스트되고 입증 된 개발 패러다임을 제공하여 개발 프로세스 속도를 높일 수 있습니다.
|
||||
|
||||
디자인 패턴을 사용하면 주요 문제를 유발하는 미묘한 이슈들을 방지하는 데 도움이 되며 또한 패턴에 익숙한 개발자와 아키텍트의 코드 가독성을 향상시킵니다.
|
||||
디자인 패턴을 재사용하면 주요 문제를 유발하는 미묘한 이슈들을 방지하는데 도움이 되며 또한 패턴에 익숙한 코더와 아키텍트의 코드 가독성도 향상됩니다.
|
||||
|
||||
# 시작하기
|
||||
|
||||
이 사이트는 Java 디자인 패턴을 설명합니다. 이 솔루션은 오픈 소스 커뮤니티의 경험이 많은 개발자와 설계자가 개발했습니다. 패턴은 높은 수준의 설명이나 소스 코드를 통해 찾아볼 수 있습니다. 소스 코드 예제는 잘 설명되어 있으며 특정 패턴을 구현하는 방법을 알려주는 프로그래밍 튜토리얼로 사용할 수 있습니다. 우리는 가장 널리 알려지고 실무에서 입증된 오픈 소스 Java 기술을 사용합니다.
|
||||
이 사이트는 Java 디자인 패턴을 보여줍니다. 이 솔루션은 오픈 소스 커뮤니티의 경험이 많은 프로그래머와 설계자가 개발했습니다. 패턴은 높은 수준의 설명이나 소스 코드를 통해 찾아 볼 수 있습니다. 소스 코드 예제는 잘 설명되어 있으며 특정 패턴을 구현하는 방법을 알려주는 프로그래밍 튜토리얼로 생각할 수 있습니다. 우리는 가장 널리 알려지고 실무에서 입증된 오픈 소스 Java 기술을 사용합니다.
|
||||
|
||||
자료를 살펴보기 전에 다양한 [소프트웨어 설계 원칙](https://java-design-patterns.com/principles/)을 숙지해야 합니다.
|
||||
자료를 살펴보기 전에 다양한 [소프트웨어 설계 원칙](https://java-design-patterns.com/principles/)을 숙지해야합니다.
|
||||
|
||||
모든 디자인 패턴은 가능한 한 심플해야 합니다. 소프트웨어 개발의 KISS, YAGNI 원칙을 지켜야 하며, 문제를 해결할 수 있는 가장 심플한 일을 해야 합니다. 복잡한 디자인 패턴은 실용적이고 확장성을 위해 필요할 때만 도입되어야 합니다.
|
||||
모든 디자인은 가능한 한 단순해야합니다. 당신은 KISS, YAGNI로 시작해야하며, 원칙을 작동 할 수 있는 가장 단순한 일을 해야합니다. 복잡성과 패턴은 실용적인 확장성을 위해 필요할 때만 도입되어야합니다.
|
||||
|
||||
이러한 개념에 익숙해지면 아래와 같은 방법으로 [사용 가능한 디자인 패턴](https://java-design-patterns.com/patterns/) 중 하나를 선택하여 문제를 해결할 수 있습니다.
|
||||
이러한 개념에 익숙해지면 다음 접근 방식 중 하나를 이용하여 [사용 가능한 디자인 패턴](https://java-design-patterns.com/patterns/)으로 드릴다운 할 수 있습니다.
|
||||
|
||||
- 이름으로 특정 패턴을 검색합니다. 찾는 패턴이 없다면 [여기](https://github.com/iluwatar/java-design-patterns/issues)에서 새 패턴을 요청하세요.
|
||||
- `Performance`, `Gang of Four` 또는 `Data access` 등의 태그로 검색하세요.
|
||||
- `Creational`, `Behavioral` 등의 패턴 카테고리로 검색하세요.
|
||||
- 이름으로 특정 패턴을 검색합니다. 찾을 수 없습니까? [여기](https://github.com/iluwatar/java-design-patterns/issues)에서 새 패턴을 보고하십시오.
|
||||
- `Performance`, `Gang of Four` 또는 `Data access` 태그 사용.
|
||||
- 패턴 카테고리, `Creational`, `Behavioral` 및 기타 사용
|
||||
|
||||
이 사이트에서 제공하는 객체 지향 솔루션이 여러분의 아키텍처에 유용하고 사용되고 우리가 개발 한 것만큼 재미있게 배우기를 바랍니다.
|
||||
이 사이트에 제시된 객체 지향 솔루션이 여러분의 아키텍처에서 유용하고 우리가 개발 한 것만큼 재미있게 배우기를 바랍니다.
|
||||
|
||||
# 기여하는 방법
|
||||
|
||||
프로젝트에 기여할 의향이 있다면 [developer wiki](https://github.com/iluwatar/java-design-patterns/wiki)에서 관련 정보를 찾을 수 있습니다. [Gitter chatroom](https://gitter.im/iluwatar/java-design-patterns)에서 귀하를 돕고 질문에 답변해 드리겠습니다.
|
||||
프로젝트에 기여할 의향이 있다면 [developer wiki](https://github.com/iluwatar/java-design-patterns/wiki)에서 관련 정보를 찾을 수 있습니다. [Gitter chatroom](https://gitter.im/iluwatar/java-design-patterns)에서 귀하를 돕고 질문에 답변 해 드리겠습니다.
|
||||
|
||||
# 특허
|
||||
|
||||
이 프로젝트는 MIT 라이센스 조건에 따라 라이센스가 적용됩니다.
|
||||
이 프로젝트는 MIT 라이센스 조건에 따라 라이센스가 부여됩니다.
|
||||
|
||||
# 기여자
|
||||
|
||||
|
@ -1,185 +0,0 @@
|
||||
---
|
||||
layout: pattern
|
||||
title: Strategy
|
||||
folder: strategy
|
||||
permalink: /patterns/strategy/
|
||||
categories: Behavioral
|
||||
tags:
|
||||
- Gang of Four
|
||||
---
|
||||
|
||||
## 동의어
|
||||
|
||||
정책(Policy) 패턴
|
||||
|
||||
## 의도
|
||||
|
||||
알고리즘군을 정의하고 각 알고리즘을 캡슐화하고 상호 변경 가능하게 만듭니다. 전략(Strategy) 패턴을 사용하면 알고리즘이 이를 사용하는 클라이언트와 독립적일 수 있습니다.
|
||||
|
||||
## 설명
|
||||
|
||||
실제 예제
|
||||
|
||||
> 드래곤을 사냥하는 것은 위험한 일입니다. 경험이 쌓이면 쉬워집니다. 베테랑 사냥꾼들은 서로 다른 유형의 드래곤에 대해 서로 다른 전투 전략을 개발했습니다.
|
||||
|
||||
평범한 말로는
|
||||
|
||||
> 전략(Strategy) 패턴을 사용하면 런타임에 가장 적합한 알고리즘을 선택할 수 있습니다.
|
||||
|
||||
Wikipedia는
|
||||
|
||||
> 컴퓨터 프로그래밍에서 전략 패턴(정책 패턴이라고도 함)은 런타임에 알고리즘을 선택할 수 있는 행동 소프트웨어 디자인 패턴입니다.
|
||||
|
||||
**프로그래밍 예**
|
||||
|
||||
먼저 드래곤 사냥 전략 인터페이스와 그 구현을 살펴봅니다.
|
||||
|
||||
```java
|
||||
@FunctionalInterface
|
||||
public interface DragonSlayingStrategy {
|
||||
|
||||
void execute();
|
||||
}
|
||||
|
||||
@Slf4j
|
||||
public class MeleeStrategy implements DragonSlayingStrategy {
|
||||
|
||||
@Override
|
||||
public void execute() {
|
||||
LOGGER.info("With your Excalibur you sever the dragon's head!");
|
||||
}
|
||||
}
|
||||
|
||||
@Slf4j
|
||||
public class ProjectileStrategy implements DragonSlayingStrategy {
|
||||
|
||||
@Override
|
||||
public void execute() {
|
||||
LOGGER.info("You shoot the dragon with the magical crossbow and it falls dead on the ground!");
|
||||
}
|
||||
}
|
||||
|
||||
@Slf4j
|
||||
public class SpellStrategy implements DragonSlayingStrategy {
|
||||
|
||||
@Override
|
||||
public void execute() {
|
||||
LOGGER.info("You cast the spell of disintegration and the dragon vaporizes in a pile of dust!");
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
그리고 여기 상대하는 드래곤에 따라 자신의 전투 전략을 선택할 수 있는 강력한 드래곤 슬레이어가 있습니다.
|
||||
|
||||
```java
|
||||
public class DragonSlayer {
|
||||
|
||||
private DragonSlayingStrategy strategy;
|
||||
|
||||
public DragonSlayer(DragonSlayingStrategy strategy) {
|
||||
this.strategy = strategy;
|
||||
}
|
||||
|
||||
public void changeStrategy(DragonSlayingStrategy strategy) {
|
||||
this.strategy = strategy;
|
||||
}
|
||||
|
||||
public void goToBattle() {
|
||||
strategy.execute();
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
마지막으로 여기 드래곤 슬레이어가 행동합니다.
|
||||
|
||||
```java
|
||||
LOGGER.info("Green dragon spotted ahead!");
|
||||
var dragonSlayer = new DragonSlayer(new MeleeStrategy());
|
||||
dragonSlayer.goToBattle();
|
||||
LOGGER.info("Red dragon emerges.");
|
||||
dragonSlayer.changeStrategy(new ProjectileStrategy());
|
||||
dragonSlayer.goToBattle();
|
||||
LOGGER.info("Black dragon lands before you.");
|
||||
dragonSlayer.changeStrategy(new SpellStrategy());
|
||||
dragonSlayer.goToBattle();
|
||||
```
|
||||
|
||||
프로그램 출력:
|
||||
|
||||
```
|
||||
Green dragon spotted ahead!
|
||||
With your Excalibur you sever the dragon's head!
|
||||
Red dragon emerges.
|
||||
You shoot the dragon with the magical crossbow and it falls dead on the ground!
|
||||
Black dragon lands before you.
|
||||
You cast the spell of disintegration and the dragon vaporizes in a pile of dust!
|
||||
```
|
||||
|
||||
또한 Java 8의 새로운 기능인 Lambda Expressions은 구현을 위한 또 다른 접근 방식을 제공합니다:
|
||||
|
||||
```java
|
||||
public class LambdaStrategy {
|
||||
|
||||
private static final Logger LOGGER = LoggerFactory.getLogger(LambdaStrategy.class);
|
||||
|
||||
public enum Strategy implements DragonSlayingStrategy {
|
||||
MeleeStrategy(() -> LOGGER.info(
|
||||
"With your Excalibur you severe the dragon's head!")),
|
||||
ProjectileStrategy(() -> LOGGER.info(
|
||||
"You shoot the dragon with the magical crossbow and it falls dead on the ground!")),
|
||||
SpellStrategy(() -> LOGGER.info(
|
||||
"You cast the spell of disintegration and the dragon vaporizes in a pile of dust!"));
|
||||
|
||||
private final DragonSlayingStrategy dragonSlayingStrategy;
|
||||
|
||||
Strategy(DragonSlayingStrategy dragonSlayingStrategy) {
|
||||
this.dragonSlayingStrategy = dragonSlayingStrategy;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void execute() {
|
||||
dragonSlayingStrategy.execute();
|
||||
}
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
그리고 여기 드래곤 슬레이어가 행동합니다.
|
||||
|
||||
```java
|
||||
LOGGER.info("Green dragon spotted ahead!");
|
||||
dragonSlayer.changeStrategy(LambdaStrategy.Strategy.MeleeStrategy);
|
||||
dragonSlayer.goToBattle();
|
||||
LOGGER.info("Red dragon emerges.");
|
||||
dragonSlayer.changeStrategy(LambdaStrategy.Strategy.ProjectileStrategy);
|
||||
dragonSlayer.goToBattle();
|
||||
LOGGER.info("Black dragon lands before you.");
|
||||
dragonSlayer.changeStrategy(LambdaStrategy.Strategy.SpellStrategy);
|
||||
dragonSlayer.goToBattle();
|
||||
```
|
||||
|
||||
프로그램 출력은 위와 동일합니다.
|
||||
|
||||
## 클래스 다이어그램
|
||||
|
||||

|
||||
|
||||
## 적용 가능성
|
||||
|
||||
다음과 같은 경우 전략(Strategy) 패턴을 사용합니다.
|
||||
|
||||
* 비슷한 클래스들이 동작 만 다른 경우가 많이 있습니다. 전략 패턴은 여러 동작 중 하나를 클래스로 구성하는 방법을 제공합니다.
|
||||
* 알고리즘의 다양한 변형이 필요합니다. 예를 들어 다양한 공간 / 시간 절충을 반영하는 알고리즘을 정의할 수 있습니다. 이러한 변형이 알고리즘의 클래스 계층 구조로 구현될 때 전략 패턴을 사용할 수 있습니다.
|
||||
* 알고리즘은 클라이언트가 알 필요 없는 데이터를 사용합니다. 전략 패턴을 사용하여 복잡한 알고리즘 별 데이터 구조가 노출되지 않도록 합니다.
|
||||
* 클래스는 많은 동작을 정의하며 이러한 동작은 작업에서 여러 조건문으로 나타납니다. 많은 조건부 대신 관련 조건부 분기를 자체 전략 클래스로 이동하세요.
|
||||
|
||||
## 튜토리얼
|
||||
|
||||
* [전략 패턴 튜토리얼](https://www.journaldev.com/1754/strategy-design-pattern-in-java-example-tutorial)
|
||||
|
||||
## 크레딧
|
||||
|
||||
* [디자인 패턴: 재사용 가능한 객체 지향 소프트웨어의 요소](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)
|
||||
* [자바의 함수형 프로그래밍: Java 8 Lambda 표현식의 강력한 기능 활용](https://www.amazon.com/gp/product/1937785467/ref=as_li_tl?ie=UTF8&camp=1789&creative=9325&creativeASIN=1937785467&linkCode=as2&tag=javadesignpat-20&linkId=7e4e2fb7a141631491534255252fd08b)
|
||||
* [헤드 퍼스트 디자인 패턴: 두뇌 친화적인 가이드](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)
|
||||
* [패턴으로 리팩토링](https://www.amazon.com/gp/product/0321213351/ref=as_li_tl?ie=UTF8&camp=1789&creative=9325&creativeASIN=0321213351&linkCode=as2&tag=javadesignpat-20&linkId=2a76fcb387234bc71b1c61150b3cc3a7)
|
3
pom.xml
3
pom.xml
@ -75,7 +75,7 @@
|
||||
<directory-maven-plugin.version>0.3.1</directory-maven-plugin.version>
|
||||
<license-maven-plugin.version>3.0</license-maven-plugin.version>
|
||||
<urm-maven-plugin.version>1.4.8</urm-maven-plugin.version>
|
||||
<commons-io.version>2.7</commons-io.version>
|
||||
<commons-io.version>2.6</commons-io.version>
|
||||
|
||||
<!-- SonarCloud -->
|
||||
<sonar.host.url>https://sonarcloud.io</sonar.host.url>
|
||||
@ -224,7 +224,6 @@
|
||||
<module>parameter-object</module>
|
||||
<module>active-object</module>
|
||||
<module>model-view-viewmodel</module>
|
||||
<module>composite-entity</module>
|
||||
</modules>
|
||||
|
||||
<repositories>
|
||||
|
@ -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
|
||||
```
|
||||
|
||||
## 类图
|
||||
|
||||

|
||||
|
||||
## 适用性
|
||||
|
||||
使用抽象文档模式当
|
||||
|
||||
* 需要即时添加新属性
|
||||
* 你想要一种灵活的方式来以树状结构组织域
|
||||
* 你想要更宽松的耦合系统
|
||||
|
||||
## 鸣谢
|
||||
|
||||
* [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)
|
@ -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
|
||||
}
|
||||
```
|
||||
|
||||
## 类图
|
||||
|
||||

|
||||
|
||||
|
||||
## 适用性
|
||||
|
||||
在以下情况下使用抽象工厂模式
|
||||
|
||||
* 该系统应独立于其产品的创建,组成和表示方式
|
||||
* 系统应配置有多个产品系列之一
|
||||
* 相关产品对象系列旨在一起使用,你需要强制执行此约束
|
||||
* 你想提供产品的类库,并且只想暴露它们的接口,而不是它们的实现。
|
||||
* 从概念上讲,依赖项的生存期比使用者的生存期短。
|
||||
* 你需要一个运行时值来构建特定的依赖关系
|
||||
* 你想决定在运行时从系列中调用哪种产品。
|
||||
* 你需要提供一个或更多仅在运行时才知道的参数,然后才能解决依赖关系。
|
||||
* 当你需要产品之间的一致性时
|
||||
* 在向程序添加新产品或产品系列时,您不想更改现有代码。
|
||||
|
||||
示例场景
|
||||
|
||||
* 在运行时在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)
|
@ -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);
|
||||
}
|
||||
```
|
||||
|
||||
## 类图
|
||||
|
||||

|
@ -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.
|
||||
```
|
||||
|
||||
## 类图
|
||||
|
||||

|
||||
|
||||
## 适用性
|
||||
|
||||
以下情况可以使用此模式:
|
||||
|
||||
* 需要在现有层次结构中添加新功能而无需更改或影响该层次结构时。
|
||||
* 当某些功能在层次结构上运行,但不属于层次结构本身时。 例如 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)
|
@ -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}
|
||||
```
|
||||
|
||||
## 类图
|
||||
|
||||

|
||||
|
||||
## 适用性
|
||||
|
||||
当需要各种微服务的统一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)
|
@ -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
|
||||
```
|
||||
|
||||
## 类图
|
||||
|
||||

|
||||
|
||||
## 适用性
|
||||
|
||||
大使适用于无法修改或极难修改的旧式远程服务。 可以在客户端上实现连接性的功能,而无需更改远程服务。
|
||||
|
||||
* 大使提供了用于远程服务的本地接口。
|
||||
* 大使在客户端上提供日志记录,断路,重试和安全性。
|
||||
|
||||
## 典型用例
|
||||
|
||||
* 控制对另一个对象的访问
|
||||
* 实现日志
|
||||
* 卸载远程服务任务
|
||||
* 简化网络连接
|
||||
|
||||
## 已知使用
|
||||
|
||||
* [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)
|
@ -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;
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
## 类图
|
||||

|
||||
|
||||
## 适用性
|
||||
|
||||
在以下情况下使用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)
|
@ -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)
|
@ -1,160 +0,0 @@
|
||||
---
|
||||
layout: pattern
|
||||
title: Business Delegate
|
||||
folder: business-delegate
|
||||
permalink: /patterns/business-delegate/
|
||||
categories: Structural
|
||||
tags:
|
||||
- Decoupling
|
||||
---
|
||||
|
||||
## 作用
|
||||
|
||||
业务委托模式(译者:国内也有翻译成业务代表模式)在表现层和业务层之间增加了一个抽象层。通过使用该模式,我们获得了各层之间的松散耦合,并封装了关于如何定位、连接和与构成应用程序的业务对象进行交互的知识。
|
||||
|
||||
## 解释
|
||||
|
||||
真实世界的案例
|
||||
|
||||
> 一个手机应用程序承诺将现有的任何电影传输到你的手机上。它捕获了用户的搜索关键字内容,并将其传递给业务委托层。业务委托层选择最合适的视频流服务,并从该服务进行视频播放。
|
||||
|
||||
简而言之
|
||||
|
||||
> 业务委托模式在表现层和业务层之间增加了一个抽象层。
|
||||
|
||||
维基百科的解释
|
||||
|
||||
> Business delegate is a Java EE design pattern. This pattern is directing to reduce the coupling
|
||||
> in between business services and the connected presentation tier, and to hide the implementation
|
||||
> details of services (including lookup and accessibility of EJB architecture). Business delegates
|
||||
> acts as an adaptor to invoke business objects from the presentation tier.
|
||||
>
|
||||
> 业务委托模式是一种 Java EE 设计模式。这种模式旨在减少业务服务和所连接的表现层之间的耦合度,并隐藏服务的实现细节(包括 EJB 架构的查询和可访问性)。业务代表作为一个适配器,从表现层调用业务对象。
|
||||
|
||||
**编程示例**
|
||||
|
||||
首先,我们实现了一个视频流服务的抽象,和几个具体实现。
|
||||
|
||||
```java
|
||||
public interface VideoStreamingService {
|
||||
void doProcessing();
|
||||
}
|
||||
|
||||
@Slf4j
|
||||
public class NetflixService implements VideoStreamingService {
|
||||
@Override
|
||||
public void doProcessing() {
|
||||
LOGGER.info("NetflixService is now processing");
|
||||
}
|
||||
}
|
||||
|
||||
@Slf4j
|
||||
public class YouTubeService implements VideoStreamingService {
|
||||
@Override
|
||||
public void doProcessing() {
|
||||
LOGGER.info("YouTubeService is now processing");
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
接下来,我们实现一个查询服务,用于决定使用哪个视频流服务。
|
||||
|
||||
```java
|
||||
@Setter
|
||||
public class BusinessLookup {
|
||||
|
||||
private NetflixService netflixService;
|
||||
private YouTubeService youTubeService;
|
||||
|
||||
public VideoStreamingService getBusinessService(String movie) {
|
||||
if (movie.toLowerCase(Locale.ROOT).contains("die hard")) {
|
||||
return netflixService;
|
||||
} else {
|
||||
return youTubeService;
|
||||
}
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
业务委托层使用业务查询,将电影播放请求路由到合适的视频流服务。
|
||||
|
||||
```java
|
||||
@Setter
|
||||
public class BusinessDelegate {
|
||||
|
||||
private BusinessLookup lookupService;
|
||||
|
||||
public void playbackMovie(String movie) {
|
||||
VideoStreamingService videoStreamingService = lookupService.getBusinessService(movie);
|
||||
videoStreamingService.doProcessing();
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
移动客户端利用业务委托来调用业务层。
|
||||
|
||||
```java
|
||||
public class MobileClient {
|
||||
|
||||
private final BusinessDelegate businessDelegate;
|
||||
|
||||
public MobileClient(BusinessDelegate businessDelegate) {
|
||||
this.businessDelegate = businessDelegate;
|
||||
}
|
||||
|
||||
public void playbackMovie(String movie) {
|
||||
businessDelegate.playbackMovie(movie);
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
最后,我们展示一下这个示例完整的操作。
|
||||
|
||||
```java
|
||||
public static void main(String[] args) {
|
||||
|
||||
// prepare the objects
|
||||
var businessDelegate = new BusinessDelegate();
|
||||
var businessLookup = new BusinessLookup();
|
||||
businessLookup.setNetflixService(new NetflixService());
|
||||
businessLookup.setYouTubeService(new YouTubeService());
|
||||
businessDelegate.setLookupService(businessLookup);
|
||||
|
||||
// create the client and use the business delegate
|
||||
var client = new MobileClient(businessDelegate);
|
||||
client.playbackMovie("Die Hard 2");
|
||||
client.playbackMovie("Maradona: The Greatest Ever");
|
||||
}
|
||||
```
|
||||
|
||||
以下是终端输出的内容。
|
||||
|
||||
```
|
||||
21:15:33.790 [main] INFO com.iluwatar.business.delegate.NetflixService - NetflixService is now processing
|
||||
21:15:33.794 [main] INFO com.iluwatar.business.delegate.YouTubeService - YouTubeService is now processing
|
||||
```
|
||||
|
||||
## 类图
|
||||
|
||||

|
||||
|
||||
## 相关模式
|
||||
|
||||
* [Service locator pattern](https://java-design-patterns.com/patterns/service-locator/)
|
||||
|
||||
## 适用场景
|
||||
|
||||
业务委托模式的适用场景:
|
||||
|
||||
* 你希望表现层和业务层之间是松耦合的。
|
||||
* 你想要协调对多个业务服务的调用。
|
||||
* 你想要对服务查询、服务调用进行封装。
|
||||
|
||||
## 教程
|
||||
|
||||
* [Business Delegate Pattern at TutorialsPoint](https://www.tutorialspoint.com/design_pattern/business_delegate_pattern.htm)
|
||||
|
||||
## 鸣谢
|
||||
|
||||
* [J2EE Design Patterns](https://www.amazon.com/gp/product/0596004273/ref=as_li_tl?ie=UTF8&camp=1789&creative=9325&creativeASIN=0596004273&linkCode=as2&tag=javadesignpat-20&linkId=48d37c67fb3d845b802fa9b619ad8f31)
|
||||
* [Core J2EE Patterns: Best Practices and Design Strategies](https://www.amazon.com/gp/product/0130648841/ref=as_li_qf_asin_il_tl?ie=UTF8&tag=javadesignpat-20&creative=9325&linkCode=as2&creativeASIN=0130648841&linkId=a0100de2b28c71ede8db1757fb2b5947)
|
@ -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
|
||||
```
|
||||
|
||||
## 类图
|
||||
|
||||

|
||||
|
||||
## 适用性
|
||||
|
||||
将版本号用于:
|
||||
|
||||
* 解决对数据的并发写访问
|
||||
* 强的数据一致性
|
||||
|
||||
## 教程
|
||||
* [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)
|
Reference in New Issue
Block a user