Merge remote-tracking branch 'upstream/master'

This commit is contained in:
waisuan 2015-11-02 01:38:37 +08:00
commit 37cfa4b295
23 changed files with 464 additions and 169 deletions

View File

@ -6,45 +6,44 @@ import com.iluwatar.observer.generic.GWeather;
/**
*
* The Observer pattern is a software design pattern in which an object, called
* the subject, maintains a list of its dependents, called observers, and notifies
* them automatically of any state changes, usually by calling one of their methods.
* It is mainly used to implement distributed event handling systems. The Observer
* pattern is also a key part in the familiar modelviewcontroller (MVC) architectural
* pattern. The Observer pattern is implemented in numerous programming libraries and
* systems, including almost all GUI toolkits.
* The Observer pattern is a software design pattern in which an object, called the subject,
* maintains a list of its dependents, called observers, and notifies them automatically of any
* state changes, usually by calling one of their methods. It is mainly used to implement
* distributed event handling systems. The Observer pattern is also a key part in the familiar
* modelviewcontroller (MVC) architectural pattern. The Observer pattern is implemented in
* numerous programming libraries and systems, including almost all GUI toolkits.
* <p>
* In this example {@link Weather} has a state that can be observed. The {@link Orcs}
* and {@link Hobbits} register as observers and receive notifications when the
* {@link Weather} changes.
* In this example {@link Weather} has a state that can be observed. The {@link Orcs} and
* {@link Hobbits} register as observers and receive notifications when the {@link Weather} changes.
*
*/
public class App {
/**
* Program entry point
* @param args command line args
*/
public static void main(String[] args) {
/**
* Program entry point
*
* @param args command line args
*/
public static void main(String[] args) {
Weather weather = new Weather();
weather.addObserver(new Orcs());
weather.addObserver(new Hobbits());
Weather weather = new Weather();
weather.addObserver(new Orcs());
weather.addObserver(new Hobbits());
weather.timePasses();
weather.timePasses();
weather.timePasses();
weather.timePasses();
weather.timePasses();
weather.timePasses();
weather.timePasses();
weather.timePasses();
// Generic observer inspired by Java Generics and Collection by Naftalin & Wadler
System.out.println("\n--Running generic version--");
GWeather gWeather = new GWeather();
gWeather.addObserver(new GOrcs());
gWeather.addObserver(new GHobbits());
// Generic observer inspired by Java Generics and Collection by Naftalin & Wadler
System.out.println("\n--Running generic version--");
GWeather gWeather = new GWeather();
gWeather.addObserver(new GOrcs());
gWeather.addObserver(new GHobbits());
gWeather.timePasses();
gWeather.timePasses();
gWeather.timePasses();
gWeather.timePasses();
}
gWeather.timePasses();
gWeather.timePasses();
gWeather.timePasses();
gWeather.timePasses();
}
}

View File

@ -7,24 +7,23 @@ package com.iluwatar.observer;
*/
public class Hobbits implements WeatherObserver {
@Override
public void update(WeatherType currentWeather) {
switch (currentWeather) {
case COLD:
System.out.println("The hobbits are shivering in the cold weather.");
break;
case RAINY:
System.out.println("The hobbits look for cover from the rain.");
break;
case SUNNY:
System.out.println("The happy hobbits bade in the warm sun.");
break;
case WINDY:
System.out.println("The hobbits hold their hats tightly in the windy weather.");
break;
default:
break;
}
}
@Override
public void update(WeatherType currentWeather) {
switch (currentWeather) {
case COLD:
System.out.println("The hobbits are shivering in the cold weather.");
break;
case RAINY:
System.out.println("The hobbits look for cover from the rain.");
break;
case SUNNY:
System.out.println("The happy hobbits bade in the warm sun.");
break;
case WINDY:
System.out.println("The hobbits hold their hats tightly in the windy weather.");
break;
default:
break;
}
}
}

View File

@ -7,24 +7,23 @@ package com.iluwatar.observer;
*/
public class Orcs implements WeatherObserver {
@Override
public void update(WeatherType currentWeather) {
switch (currentWeather) {
case COLD:
System.out.println("The orcs are freezing cold.");
break;
case RAINY:
System.out.println("The orcs are dripping wet.");
break;
case SUNNY:
System.out.println("The sun hurts the orcs' eyes.");
break;
case WINDY:
System.out.println("The orc smell almost vanishes in the wind.");
break;
default:
break;
}
}
@Override
public void update(WeatherType currentWeather) {
switch (currentWeather) {
case COLD:
System.out.println("The orcs are freezing cold.");
break;
case RAINY:
System.out.println("The orcs are dripping wet.");
break;
case SUNNY:
System.out.println("The sun hurts the orcs' eyes.");
break;
case WINDY:
System.out.println("The orc smell almost vanishes in the wind.");
break;
default:
break;
}
}
}

View File

@ -5,38 +5,38 @@ import java.util.List;
/**
*
* Weather can be observed by implementing {@link WeatherObserver} interface and
* registering as listener.
* Weather can be observed by implementing {@link WeatherObserver} interface and registering as
* listener.
*
*/
public class Weather {
private WeatherType currentWeather;
private List<WeatherObserver> observers;
private WeatherType currentWeather;
private List<WeatherObserver> observers;
public Weather() {
observers = new ArrayList<>();
currentWeather = WeatherType.SUNNY;
}
public Weather() {
observers = new ArrayList<>();
currentWeather = WeatherType.SUNNY;
}
public void addObserver(WeatherObserver obs) {
observers.add(obs);
}
public void addObserver(WeatherObserver obs) {
observers.add(obs);
}
public void removeObserver(WeatherObserver obs) {
observers.remove(obs);
}
public void removeObserver(WeatherObserver obs) {
observers.remove(obs);
}
public void timePasses() {
WeatherType[] enumValues = WeatherType.values();
currentWeather = enumValues[(currentWeather.ordinal() + 1) % enumValues.length];
System.out.println("The weather changed to " + currentWeather + ".");
notifyObservers();
}
public void timePasses() {
WeatherType[] enumValues = WeatherType.values();
currentWeather = enumValues[(currentWeather.ordinal() + 1) % enumValues.length];
System.out.println("The weather changed to " + currentWeather + ".");
notifyObservers();
}
private void notifyObservers() {
for (WeatherObserver obs : observers) {
obs.update(currentWeather);
}
}
private void notifyObservers() {
for (WeatherObserver obs : observers) {
obs.update(currentWeather);
}
}
}

View File

@ -7,6 +7,6 @@ package com.iluwatar.observer;
*/
public interface WeatherObserver {
void update(WeatherType currentWeather);
void update(WeatherType currentWeather);
}

View File

@ -7,11 +7,10 @@ package com.iluwatar.observer;
*/
public enum WeatherType {
SUNNY, RAINY, WINDY, COLD;
@Override
public String toString() {
return this.name().toLowerCase();
}
SUNNY, RAINY, WINDY, COLD;
@Override
public String toString() {
return this.name().toLowerCase();
}
}

View File

@ -8,23 +8,23 @@ import com.iluwatar.observer.WeatherType;
*
*/
public class GHobbits implements Race {
@Override
public void update(GWeather weather, WeatherType weatherType) {
switch (weatherType) {
case COLD:
System.out.println("The hobbits are shivering in the cold weather.");
break;
case RAINY:
System.out.println("The hobbits look for cover from the rain.");
break;
case SUNNY:
System.out.println("The happy hobbits bade in the warm sun.");
break;
case WINDY:
System.out.println("The hobbits hold their hats tightly in the windy weather.");
break;
default:
break;
}
@Override
public void update(GWeather weather, WeatherType weatherType) {
switch (weatherType) {
case COLD:
System.out.println("The hobbits are shivering in the cold weather.");
break;
case RAINY:
System.out.println("The hobbits look for cover from the rain.");
break;
case SUNNY:
System.out.println("The happy hobbits bade in the warm sun.");
break;
case WINDY:
System.out.println("The hobbits hold their hats tightly in the windy weather.");
break;
default:
break;
}
}
}

View File

@ -8,24 +8,24 @@ import com.iluwatar.observer.WeatherType;
*
*/
public class GOrcs implements Race {
@Override
public void update(GWeather weather, WeatherType weatherType) {
switch (weatherType) {
case COLD:
System.out.println("The orcs are freezing cold.");
break;
case RAINY:
System.out.println("The orcs are dripping wet.");
break;
case SUNNY:
System.out.println("The sun hurts the orcs' eyes.");
break;
case WINDY:
System.out.println("The orc smell almost vanishes in the wind.");
break;
default:
break;
}
@Override
public void update(GWeather weather, WeatherType weatherType) {
switch (weatherType) {
case COLD:
System.out.println("The orcs are freezing cold.");
break;
case RAINY:
System.out.println("The orcs are dripping wet.");
break;
case SUNNY:
System.out.println("The sun hurts the orcs' eyes.");
break;
case WINDY:
System.out.println("The orc smell almost vanishes in the wind.");
break;
default:
break;
}
}
}

View File

@ -9,16 +9,16 @@ import com.iluwatar.observer.WeatherType;
*/
public class GWeather extends Observable<GWeather, Race, WeatherType> {
private WeatherType currentWeather;
private WeatherType currentWeather;
public GWeather() {
currentWeather = WeatherType.SUNNY;
}
public GWeather() {
currentWeather = WeatherType.SUNNY;
}
public void timePasses() {
WeatherType[] enumValues = WeatherType.values();
currentWeather = enumValues[(currentWeather.ordinal() + 1) % enumValues.length];
System.out.println("The weather changed to " + currentWeather + ".");
notifyObservers(currentWeather);
}
public void timePasses() {
WeatherType[] enumValues = WeatherType.values();
currentWeather = enumValues[(currentWeather.ordinal() + 1) % enumValues.length];
System.out.println("The weather changed to " + currentWeather + ".");
notifyObservers(currentWeather);
}
}

View File

@ -12,20 +12,20 @@ import java.util.concurrent.CopyOnWriteArrayList;
*/
public abstract class Observable<S extends Observable<S, O, A>, O extends Observer<S, O, A>, A> {
protected List<O> observers;
protected List<O> observers;
public Observable() {
this.observers = new CopyOnWriteArrayList<>();
}
public Observable() {
this.observers = new CopyOnWriteArrayList<>();
}
public void addObserver(O observer) {
this.observers.add(observer);
}
public void addObserver(O observer) {
this.observers.add(observer);
}
@SuppressWarnings("unchecked")
public void notifyObservers(A argument) {
for (O observer : observers) {
observer.update((S) this, argument);
}
@SuppressWarnings("unchecked")
public void notifyObservers(A argument) {
for (O observer : observers) {
observer.update((S) this, argument);
}
}
}

View File

@ -10,5 +10,5 @@ package com.iluwatar.observer.generic;
*/
public interface Observer<S extends Observable<S, O, A>, O extends Observer<S, O, A>, A> {
void update(S subject, A argument);
void update(S subject, A argument);
}

View File

@ -11,9 +11,9 @@ import com.iluwatar.observer.App;
*/
public class AppTest {
@Test
public void test() {
String[] args = {};
App.main(args);
}
@Test
public void test() {
String[] args = {};
App.main(args);
}
}

View File

@ -56,6 +56,7 @@
<module>execute-around</module>
<module>property</module>
<module>intercepting-filter</module>
<module>producer-consumer</module>
<module>poison-pill</module>
<module>lazy-loading</module>
<module>service-layer</module>

Binary file not shown.

After

Width:  |  Height:  |  Size: 26 KiB

View File

@ -0,0 +1,74 @@
<?xml version="1.0" encoding="UTF-8"?>
<class-diagram version="1.1.8" icons="true" automaticImage="PNG" always-add-relationships="false" generalizations="true"
realizations="true" associations="true" dependencies="false" nesting-relationships="true">
<class id="1" language="java" name="com.iluwatar.producer.consumer.Item" project="producer-consumer"
file="/producer-consumer/src/main/java/com/iluwatar/producer/consumer/Item.java" binary="false"
corner="BOTTOM_RIGHT">
<position height="-1" width="-1" x="415" y="378"/>
<display autosize="true" stereotype="true" package="true" initial-value="false" signature="true"
sort-features="false" accessors="true" visibility="true">
<attributes public="true" package="true" protected="true" private="true" static="true"/>
<operations public="true" package="true" protected="true" private="true" static="true"/>
</display>
</class>
<class id="2" language="java" name="com.iluwatar.producer.consumer.Producer" project="producer-consumer"
file="/producer-consumer/src/main/java/com/iluwatar/producer/consumer/Producer.java" binary="false"
corner="BOTTOM_RIGHT">
<position height="-1" width="-1" x="150" y="191"/>
<display autosize="true" stereotype="true" package="true" initial-value="false" signature="true"
sort-features="false" accessors="true" visibility="true">
<attributes public="true" package="true" protected="true" private="true" static="true"/>
<operations public="true" package="true" protected="true" private="true" static="true"/>
</display>
</class>
<class id="3" language="java" name="com.iluwatar.producer.consumer.Consumer" project="producer-consumer"
file="/producer-consumer/src/main/java/com/iluwatar/producer/consumer/Consumer.java" binary="false"
corner="BOTTOM_RIGHT">
<position height="-1" width="-1" x="675" y="186"/>
<display autosize="true" stereotype="true" package="true" initial-value="false" signature="true"
sort-features="false" accessors="true" visibility="true">
<attributes public="true" package="true" protected="true" private="true" static="true"/>
<operations public="true" package="true" protected="true" private="true" static="true"/>
</display>
</class>
<class id="4" language="java" name="com.iluwatar.producer.consumer.ItemQueue" project="producer-consumer"
file="/producer-consumer/src/main/java/com/iluwatar/producer/consumer/ItemQueue.java" binary="false"
corner="BOTTOM_RIGHT">
<position height="-1" width="-1" x="415" y="187"/>
<display autosize="true" stereotype="true" package="true" initial-value="false" signature="true"
sort-features="false" accessors="true" visibility="true">
<attributes public="true" package="true" protected="true" private="true" static="true"/>
<operations public="true" package="true" protected="true" private="true" static="true"/>
</display>
</class>
<association id="5">
<end type="SOURCE" refId="3" navigable="false">
<attribute id="6" name="queue"/>
<multiplicity id="7" minimum="0" maximum="1"/>
</end>
<end type="TARGET" refId="4" navigable="true"/>
<display labels="true" multiplicity="true"/>
</association>
<association id="8">
<end type="SOURCE" refId="4" navigable="false">
<attribute id="9" name="queue"/>
<multiplicity id="10" minimum="0" maximum="2147483647"/>
</end>
<end type="TARGET" refId="1" navigable="true"/>
<display labels="true" multiplicity="true"/>
</association>
<association id="11">
<end type="SOURCE" refId="2" navigable="false">
<attribute id="12" name="queue"/>
<multiplicity id="13" minimum="0" maximum="1"/>
</end>
<end type="TARGET" refId="4" navigable="true"/>
<display labels="true" multiplicity="true"/>
</association>
<classifier-display autosize="true" stereotype="true" package="true" initial-value="false" signature="true"
sort-features="false" accessors="true" visibility="true">
<attributes public="true" package="true" protected="true" private="true" static="true"/>
<operations public="true" package="true" protected="true" private="true" static="true"/>
</classifier-display>
<association-display labels="true" multiplicity="true"/>
</class-diagram>

View File

@ -0,0 +1,22 @@
---
layout: pattern
title: Producer Consumer
folder: producer-consumer
permalink: /patterns/producer-consumer/
categories: Other
tags: Java
---
**Intent:** Producer Consumer Design pattern is a classic concurrency or threading pattern which reduces
coupling between Producer and Consumer by separating Identification of work with Execution of
Work..
![alt text](./etc/producer-consumer.png "Producer Consumer")
**Applicability:** Use the Producer Consumer idiom when
* decouple system by separate work in two process produce and consume.
* addresses the issue of different timing require to produce work or consuming work

18
producer-consumer/pom.xml Normal file
View File

@ -0,0 +1,18 @@
<?xml version="1.0"?>
<project xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd" xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>com.iluwatar</groupId>
<artifactId>java-design-patterns</artifactId>
<version>1.7.0</version>
</parent>
<artifactId>producer-consumer</artifactId>
<dependencies>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<scope>test</scope>
</dependency>
</dependencies>
</project>

View File

@ -0,0 +1,57 @@
package com.iluwatar.producer.consumer;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;
/**
* Producer Consumer Design pattern is a classic concurrency or threading pattern which reduces
* coupling between Producer and Consumer by separating Identification of work with Execution of
* Work.
* <p>
* In producer consumer design pattern a shared queue is used to control the flow and this
* separation allows you to code producer and consumer separately. It also addresses the issue of
* different timing require to produce item or consuming item. by using producer consumer pattern
* both Producer and Consumer Thread can work with different speed.
*
*/
public class App {
/**
* Program entry point
*
* @param args command line args
*/
public static void main(String[] args) {
ItemQueue queue = new ItemQueue();
ExecutorService executorService = Executors.newFixedThreadPool(5);
for (int i = 0; i < 2; i++) {
final Producer producer = new Producer("Producer_" + i, queue);
executorService.submit(() -> {
while (true) {
producer.produce();
}
});
};
for (int i = 0; i < 3; i++) {
final Consumer consumer = new Consumer("Consumer_" + i, queue);
executorService.submit(() -> {
while (true) {
consumer.consume();
}
});
}
executorService.shutdown();
try {
executorService.awaitTermination(10, TimeUnit.SECONDS);
executorService.shutdownNow();
} catch (InterruptedException e) {
System.out.println("Error waiting for ExecutorService shutdown");
}
}
}

View File

@ -0,0 +1,24 @@
package com.iluwatar.producer.consumer;
/**
* Class responsible for consume the {@link Item} produced by {@link Producer}
*/
public class Consumer {
private final ItemQueue queue;
private final String name;
public Consumer(String name, ItemQueue queue) {
this.name = name;
this.queue = queue;
}
public void consume() throws InterruptedException {
Item item = queue.take();
System.out.println(String.format("Consumer [%s] consume item [%s] produced by [%s]", name,
item.getId(), item.getProducer()));
}
}

View File

@ -0,0 +1,27 @@
package com.iluwatar.producer.consumer;
/**
* Class take part of an {@link Producer}-{@link Consumer} exchange.
*/
public class Item {
private String producer;
private int id;
public Item(String producer, int id) {
this.id = id;
this.producer = producer;
}
public int getId() {
return id;
}
public String getProducer() {
return producer;
}
}

View File

@ -0,0 +1,27 @@
package com.iluwatar.producer.consumer;
import java.util.concurrent.LinkedBlockingQueue;
/**
* Class as a channel for {@link Producer}-{@link Consumer} exchange.
*/
public class ItemQueue {
private LinkedBlockingQueue<Item> queue;
public ItemQueue() {
queue = new LinkedBlockingQueue<Item>(5);
}
public void put(Item item) throws InterruptedException {
queue.put(item);
}
public Item take() throws InterruptedException {
return queue.take();
}
}

View File

@ -0,0 +1,29 @@
package com.iluwatar.producer.consumer;
import java.util.Random;
/**
* Class responsible for producing unit of work that can be expressed as {@link Item} and submitted
* to queue
*/
public class Producer {
private final ItemQueue queue;
private final String name;
private int itemId = 0;
public Producer(String name, ItemQueue queue) {
this.name = name;
this.queue = queue;
}
public void produce() throws InterruptedException {
Item item = new Item(name, itemId++);
queue.put(item);
Random random = new Random();
Thread.sleep(random.nextInt(2000));
}
}

View File

@ -0,0 +1,20 @@
package com.iluwatar.poison.pill;
import org.junit.Test;
import com.iluwatar.producer.consumer.App;
/**
*
* Application test
*
*/
public class AppTest {
@Test
public void test() throws Exception {
String[] args = {};
App.main(args);
}
}