Merge pull request #1178 from ali4j/Development

Adding Proxy Design Pattern
This commit is contained in:
Yang Libin 2019-11-28 11:33:47 +08:00 committed by GitHub
commit 6ad2c9ff3b
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
3 changed files with 95 additions and 0 deletions

View File

@ -0,0 +1,31 @@
package com.designpatterns.structural.proxy.president;
import com.designpatterns.creational.singleton.Singleton;
/**
* This is a class which is gonna be proxied by PresidentSecretary.
* Whenever any citizen decides to contact the President, they have to talk to the Secretary.
*/
public class President {
private volatile static President instance = null;
private President() {}
static President getInstance() {
if (instance == null) {
synchronized (Singleton.class) {
if (instance == null) {
instance = new President();
}
}
}
return instance;
}
void talkToThePresident(String message){
System.out.println("President: I have received the message:" + message);
}
}

View File

@ -0,0 +1,25 @@
package com.designpatterns.structural.proxy.president;
public class PresidentSecretary {
private President president;
public PresidentSecretary() {
this.president = President.getInstance();
}
public void leaveValidMessageForPresident(String message){
if(!isMessageValid(message))
throw new RuntimeException("invalid message");
System.out.println("Secretary: message is being sent to the President...");
president.talkToThePresident(message);
System.out.println("Secretary: message is sent to the President.");
}
private boolean isMessageValid(String message) {
return message != null && !message.isEmpty() && message.length() >= 10 && message.length() <= 100;
}
}

View File

@ -0,0 +1,39 @@
package com.designpatterns.structural.proxy;
import com.designpatterns.structural.proxy.president.PresidentSecretary;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.Test;
public class Citizen {
private PresidentSecretary presidentSecretary = new PresidentSecretary();
@Test
public void talkToPresident_secretaryShouldRejectTooShortMessage() {
String message = "Hi there.";
Assertions.assertThrows(RuntimeException.class, () -> {
presidentSecretary.leaveValidMessageForPresident(message);
});
}
@Test
public void talkToPresident_secretaryShouldRejectTooLongMessage() {
String message = "Hi there. this is a message about some personal issue which I have decided to share with Mr.President.";
Assertions.assertThrows(RuntimeException.class, () -> {
presidentSecretary.leaveValidMessageForPresident(message);
});
}
@Test
public void talkToPresident_secretaryShouldAcceptTheMessage() {
String message = "Hello Mr.President";
presidentSecretary.leaveValidMessageForPresident(message);
Assertions.assertTrue(true);
}
}