Skip to content

Commit

Permalink
add pattern
Browse files Browse the repository at this point in the history
  • Loading branch information
Besok committed Oct 24, 2019
1 parent 20b4195 commit 630532c
Show file tree
Hide file tree
Showing 14 changed files with 321 additions and 54 deletions.
12 changes: 4 additions & 8 deletions role-object/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -20,14 +20,10 @@ individual objects, different contexts are kept separate and system configuratio

## Applicability
Use the Role Object pattern, if:
- you want to handle a key abstraction in different contexts and you do not want to put the resulting contextspecific interfaces into the same class interface.
Words: 4895 Page 3 of 11
- you want to handle the available roles dynamically so that they can be attached and removed on demand, that is
at runtime, rather than fixing them statically at compile-time.
- you want to treat the extensions transparently and need to preserve the logical object identity of the resulting
object conglomerate.
- you want to keep role/client pairs independent from each other so that changes to a role do not affect clients
that are not interested in that role.
- you want to handle a key abstraction in different contexts and you do not want to put the resulting context specific interfaces into the same class interface.
- you want to handle the available roles dynamically so that they can be attached and removed on demand, that is at runtime, rather than fixing them statically at compile-time.
- you want to treat the extensions transparently and need to preserve the logical object identity of the resultingobject conglomerate.
- you want to keep role/client pairs independent from each other so that changes to a role do not affect clients that are not interested in that role.

## Credits
- [Hillside - Role object pattern](https://hillside.net/plop/plop97/Proceedings/riehle.pdf)
Expand Down
8 changes: 7 additions & 1 deletion role-object/pom.xml
Original file line number Diff line number Diff line change
Expand Up @@ -33,6 +33,12 @@
</parent>

<artifactId>role-object</artifactId>
<dependencies/>
<dependencies>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<scope>test</scope>
</dependency>
</dependencies>

</project>
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,11 @@
*/
package com.iluwatar.roleobject;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import static com.iluwatar.roleobject.Role.*;

/**
* The Role Object pattern suggests to model context-specific views
* of an object as separate role objects which are
Expand All @@ -34,12 +39,12 @@
* investor, respectively. Both roles could as well be played by a single Customer object.
* The common superclass for customer-specific roles is provided by CustomerRole,
* which also supports the Customer interface.
* <p>
* The CustomerRole class is abstract and not meant to be instantiated.
* Concrete subclasses of CustomerRole, for example Borrower or Investor,
* define and implement the interface for specific roles. It is only
* these subclasses which are instantiated at runtime.
* The Borrower class defines the context-specific view of
* Customer objects as needed by the loan department.
* The Borrower class defines the context-specific view of Customer objects as needed by the loan department.
* It defines additional operations to manage the customer’s
* credits and securities. Similarly, the Investor class adds operations specific
* to the investment department’s view of customers.
Expand All @@ -48,13 +53,40 @@
* Customer instance through its Customer interface. The loan application may want to check whether the Customer
* object plays the role of Borrower.
* To this end it calls hasRole() with a suitable role specification. For the purpose of
* our example, let’s assume we can name roles with a simple string.
* If the Customer object can play the role named
* “Borrower,” the loan application will ask it to return a reference to the corresponding object.
* our example, let’s assume we can name roles with enum.
* If the Customer object can play the role named “Borrower,” the loan application will ask it to return a reference to the corresponding object.
* The loan application may now use this reference to call Borrower-specific operations.
*
*/
public class ApplicationRoleObject {

private static final Logger logger = LoggerFactory.getLogger(Role.class);

public static void main(String[] args) {
Customer customer = Customer.newCustomer(Borrower, Investor);

logger.info(" the new customer created : {}", customer);

boolean hasBorrowerRole = customer.hasRole(Borrower);
logger.info(" customer has a borrowed role - {}", hasBorrowerRole);
boolean hasInvestorRole = customer.hasRole(Investor);
logger.info(" customer has an investor role - {}", hasInvestorRole);

customer.getRole(Investor, InvestorRole.class)
.ifPresent(inv -> {
inv.setAmountToInvest(1000);
inv.setName("Billy");
});
customer.getRole(Borrower, BorrowerRole.class)
.ifPresent(inv -> inv.setName("Johny"));

customer.getRole(Investor, InvestorRole.class)
.map(InvestorRole::invest)
.ifPresent(logger::info);

customer.getRole(Borrower, BorrowerRole.class)
.map(BorrowerRole::borrow)
.ifPresent(logger::info);
}


}
Original file line number Diff line number Diff line change
@@ -1,4 +1,19 @@
package com.iluwatar.roleobject;

public class BorrowerRole extends CustomerRole{
private String name;

public String getName() {
return name;
}

public void setName(String name) {
this.name = name;
}

public String borrow(){
return String.join(" ",
"A borrower",name,"wants to get some money.");
}

}
47 changes: 46 additions & 1 deletion role-object/src/main/java/com/iluwatar/roleobject/Customer.java
Original file line number Diff line number Diff line change
Expand Up @@ -2,11 +2,56 @@

import java.util.Optional;

/**
* The main abstraction to work with Customer.
*/
public abstract class Customer {

/**
* Add specific role @see {@link Role}
*
* @param role to add
* @return true if the operation has been successful otherwise false
*/
public abstract boolean addRole(Role role);

/**
* Check specific role @see {@link Role}
*
* @param role to check
* @return true if the role exists otherwise false
*/

public abstract boolean hasRole(Role role);

/**
* Remove specific role @see {@link Role}
*
* @param role to remove
* @return true if the operation has been successful otherwise false
*/
public abstract boolean remRole(Role role);
public abstract <T extends Customer> Optional<T> getRole(Role role,Class<T> expectedRole);

/**
* Get specific instance associated with this role @see {@link Role}
*
* @param role to get
* @param expectedRole instance class expected to get
* @return optional with value if the instance exists and corresponds expected class
*/
public abstract <T extends Customer> Optional<T> getRole(Role role, Class<T> expectedRole);


public static Customer newCustomer() {
return new CustomerCore();
}

public static Customer newCustomer(Role... role) {
Customer customer = newCustomer();
for (Role r : role) {
customer.addRole(r);
}
return customer;
}

}
Original file line number Diff line number Diff line change
@@ -1,19 +1,30 @@
package com.iluwatar.roleobject;

import java.util.Map;
import java.util.Objects;
import java.util.Optional;

import java.util.*;

/**
* Core class to store different customer roles
*
* @see CustomerRole
* Note: not thread safe
*/
public class CustomerCore extends Customer {

private Map<Role, CustomerRole> roles;

public CustomerCore() {
roles = new HashMap<>();
}

@Override
public boolean addRole(Role role) {
return role.instance()
.map(rI -> roles.put(role, rI))
.isPresent();
return role
.instance()
.map(inst -> {
roles.put(role, inst);
return true;
})
.orElse(false);
}

@Override
Expand All @@ -28,8 +39,15 @@ public boolean remRole(Role role) {

@Override
public <T extends Customer> Optional<T> getRole(Role role, Class<T> expectedRole) {
return Optional.ofNullable(roles.get(role))
return Optional
.ofNullable(roles.get(role))
.filter(expectedRole::isInstance)
.map(expectedRole::cast);
}

@Override
public String toString() {
String roles = Arrays.toString(this.roles.keySet().toArray());
return "Customer{roles=" + roles + "}";
}
}
Original file line number Diff line number Diff line change
@@ -1,25 +1,6 @@
package com.iluwatar.roleobject;

import java.util.Optional;

public class CustomerRole extends Customer{
@Override
public boolean addRole(Role role) {
return false;
}

@Override
public boolean hasRole(Role role) {
return false;
}

@Override
public boolean remRole(Role role) {
return false;
}

@Override
public <T extends Customer> Optional<T> getRole(Role role, Class<T> expectedRole) {
return Optional.empty();
}
}
/**
* Key abstraction for segregated roles
*/
public abstract class CustomerRole extends CustomerCore{}
Original file line number Diff line number Diff line change
@@ -1,4 +1,27 @@
package com.iluwatar.roleobject;

public class InvestorRole extends CustomerRole{
public class InvestorRole extends CustomerRole {
private String name;
private long amountToInvest;

public String getName() {
return name;
}

public void setName(String name) {
this.name = name;
}

public long getAmountToInvest() {
return amountToInvest;
}

public void setAmountToInvest(long amountToInvest) {
this.amountToInvest = amountToInvest;
}

public String invest() {
return String.join(" ",
"Investor", name, "has invested", String.valueOf(amountToInvest), "dollars");
}
}
15 changes: 9 additions & 6 deletions role-object/src/main/java/com/iluwatar/roleobject/Role.java
Original file line number Diff line number Diff line change
Expand Up @@ -2,27 +2,30 @@

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import sun.rmi.runtime.Log;

import java.util.Optional;

/**
* Possible roles
*/
public enum Role {
Borrower(BorrowerRole.class), Investor(InvestorRole.class);

private Class<? extends Customer> typeCst;
private Class<? extends CustomerRole> typeCst;

Role(Class<? extends Customer> typeCst) {
Role(Class<? extends CustomerRole> typeCst) {
this.typeCst = typeCst;
}

private static final Logger logger = LoggerFactory.getLogger(Role.class);

@SuppressWarnings("unchecked")
<T extends CustomerRole>Optional<T> instance(){
Class<? extends Customer> typeCst = this.typeCst;
public <T extends CustomerRole> Optional<T> instance() {
Class<? extends CustomerRole> typeCst = this.typeCst;
try {
return (Optional<T>) Optional.of(typeCst.newInstance());
} catch (InstantiationException | IllegalAccessException e) {
logger.error("error creating an object",e);
logger.error("error creating an object", e);
}
return Optional.empty();
}
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
package com.iluwatar.roleobject;

import org.junit.Test;

import static org.junit.Assert.*;

public class ApplicationRoleObjectTest {

@Test
public void mainTest() {
ApplicationRoleObject.main(new String[]{});
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
package com.iluwatar.roleobject;

import org.junit.Assert;
import org.junit.Test;

import static org.junit.Assert.*;

public class BorrowerRoleTest {

@Test
public void borrowTest() {
BorrowerRole borrowerRole = new BorrowerRole();
borrowerRole.setName("test");
String res = "A borrower test wants to get some money.";

Assert.assertEquals(borrowerRole.borrow(),res);
}
}

0 comments on commit 630532c

Please sign in to comment.