-
-
Notifications
You must be signed in to change notification settings - Fork 26.1k
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
* init repo for role object * add to init * add to init * add first impl * add pattern * add license * add changes
- Loading branch information
Showing
14 changed files
with
747 additions
and
0 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,31 @@ | ||
--- | ||
layout: pattern | ||
title: Role object | ||
folder: Migration | ||
permalink: /patterns/role-object/ | ||
categories: Structural | ||
tags: | ||
- Java | ||
- Difficulty-Medium | ||
- Handle Body Pattern | ||
--- | ||
|
||
## Also known as | ||
Post pattern, Extension Object pattern | ||
|
||
## Intent | ||
Adapt an object to different client’s needs through transparently attached role objects, each one representing a role | ||
the object has to play in that client’s context. The object manages its role set dynamically. By representing roles as | ||
individual objects, different contexts are kept separate and system configuration is simplified. | ||
|
||
## 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 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) | ||
- [Role object](http://wiki.c2.com/?RoleObject) | ||
- [Fowler - Dealing with roles](https://martinfowler.com/apsupp/roles.pdf) |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,44 @@ | ||
<?xml version="1.0"?> | ||
<!-- | ||
The MIT License | ||
Copyright © 2014-2019 Ilkka Seppälä | ||
Permission is hereby granted, free of charge, to any person obtaining a copy | ||
of this software and associated documentation files (the "Software"), to deal | ||
in the Software without restriction, including without limitation the rights | ||
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell | ||
copies of the Software, and to permit persons to whom the Software is | ||
furnished to do so, subject to the following conditions: | ||
The above copyright notice and this permission notice shall be included in | ||
all copies or substantial portions of the Software. | ||
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR | ||
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, | ||
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE | ||
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER | ||
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, | ||
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN | ||
THE SOFTWARE. | ||
--> | ||
<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.22.0-SNAPSHOT</version> | ||
</parent> | ||
|
||
<artifactId>role-object</artifactId> | ||
<dependencies> | ||
<dependency> | ||
<groupId>junit</groupId> | ||
<artifactId>junit</artifactId> | ||
<scope>test</scope> | ||
</dependency> | ||
</dependencies> | ||
|
||
</project> |
93 changes: 93 additions & 0 deletions
93
role-object/src/main/java/com/iluwatar/roleobject/ApplicationRoleObject.java
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,93 @@ | ||
/* | ||
* The MIT License | ||
* Copyright © 2014-2019 Ilkka Seppälä | ||
* | ||
* Permission is hereby granted, free of charge, to any person obtaining a copy | ||
* of this software and associated documentation files (the "Software"), to deal | ||
* in the Software without restriction, including without limitation the rights | ||
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell | ||
* copies of the Software, and to permit persons to whom the Software is | ||
* furnished to do so, subject to the following conditions: | ||
* | ||
* The above copyright notice and this permission notice shall be included in | ||
* all copies or substantial portions of the Software. | ||
* | ||
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR | ||
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, | ||
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE | ||
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER | ||
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, | ||
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN | ||
* THE SOFTWARE. | ||
*/ | ||
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 | ||
* dynamically attached to and removed from the core object. | ||
* We call the resulting composite object structure, | ||
* consisting of the core and its role objects, a subject. | ||
* A subject often plays several roles and the same role is likely to | ||
* be played by different subjects. | ||
* As an example consider two different customers playing the role of borrower and | ||
* investor, respectively. Both roles could as well be played by a single {@link Customer} object. | ||
* The common superclass for customer-specific roles is provided by {@link CustomerRole}, | ||
* which also supports the {@link Customer} interface. | ||
* <p> | ||
* The {@link CustomerRole} class is abstract and not meant to be instantiated. | ||
* Concrete subclasses of {@link CustomerRole}, for example {@link BorrowerRole} or {@link InvestorRole}, | ||
* define and implement the interface for specific roles. It is only | ||
* these subclasses which are instantiated at runtime. | ||
* The {@link BorrowerRole} class defines the context-specific view of {@link Customer} objects as needed by the loan department. | ||
* It defines additional operations to manage the customer’s | ||
* credits and securities. Similarly, the {@link InvestorRole} class adds operations specific | ||
* to the investment department’s view of customers. | ||
* A client like the loan application may either work with objects of the {@link CustomerRole} class, using the interface class | ||
* {@link Customer}, or with objects of concrete {@link CustomerRole} subclasses. Suppose the loan application knows a particular | ||
* {@link Customer} instance through its {@link Customer} interface. The loan application may want to check whether the {@link Customer} | ||
* object plays the role of Borrower. | ||
* To this end it calls {@link Customer#hasRole(Role)} with a suitable role specification. For the purpose of | ||
* our example, let’s assume we can name roles with enum. | ||
* If the {@link 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); | ||
} | ||
|
||
|
||
} |
40 changes: 40 additions & 0 deletions
40
role-object/src/main/java/com/iluwatar/roleobject/BorrowerRole.java
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,40 @@ | ||
/* | ||
* The MIT License | ||
* Copyright © 2014-2019 Ilkka Seppälä | ||
* | ||
* Permission is hereby granted, free of charge, to any person obtaining a copy | ||
* of this software and associated documentation files (the "Software"), to deal | ||
* in the Software without restriction, including without limitation the rights | ||
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell | ||
* copies of the Software, and to permit persons to whom the Software is | ||
* furnished to do so, subject to the following conditions: | ||
* | ||
* The above copyright notice and this permission notice shall be included in | ||
* all copies or substantial portions of the Software. | ||
* | ||
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR | ||
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, | ||
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE | ||
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER | ||
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, | ||
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN | ||
* THE SOFTWARE. | ||
*/ | ||
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.format("Borrower %s wants to get some money.",name); | ||
} | ||
|
||
} |
79 changes: 79 additions & 0 deletions
79
role-object/src/main/java/com/iluwatar/roleobject/Customer.java
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,79 @@ | ||
/* | ||
* The MIT License | ||
* Copyright © 2014-2019 Ilkka Seppälä | ||
* | ||
* Permission is hereby granted, free of charge, to any person obtaining a copy | ||
* of this software and associated documentation files (the "Software"), to deal | ||
* in the Software without restriction, including without limitation the rights | ||
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell | ||
* copies of the Software, and to permit persons to whom the Software is | ||
* furnished to do so, subject to the following conditions: | ||
* | ||
* The above copyright notice and this permission notice shall be included in | ||
* all copies or substantial portions of the Software. | ||
* | ||
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR | ||
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, | ||
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE | ||
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER | ||
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, | ||
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN | ||
* THE SOFTWARE. | ||
*/ | ||
package com.iluwatar.roleobject; | ||
|
||
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); | ||
|
||
/** | ||
* 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; | ||
} | ||
|
||
} |
75 changes: 75 additions & 0 deletions
75
role-object/src/main/java/com/iluwatar/roleobject/CustomerCore.java
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,75 @@ | ||
/* | ||
* The MIT License | ||
* Copyright © 2014-2019 Ilkka Seppälä | ||
* | ||
* Permission is hereby granted, free of charge, to any person obtaining a copy | ||
* of this software and associated documentation files (the "Software"), to deal | ||
* in the Software without restriction, including without limitation the rights | ||
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell | ||
* copies of the Software, and to permit persons to whom the Software is | ||
* furnished to do so, subject to the following conditions: | ||
* | ||
* The above copyright notice and this permission notice shall be included in | ||
* all copies or substantial portions of the Software. | ||
* | ||
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR | ||
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, | ||
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE | ||
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER | ||
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, | ||
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN | ||
* THE SOFTWARE. | ||
*/ | ||
package com.iluwatar.roleobject; | ||
|
||
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(inst -> { | ||
roles.put(role, inst); | ||
return true; | ||
}) | ||
.orElse(false); | ||
} | ||
|
||
@Override | ||
public boolean hasRole(Role role) { | ||
return roles.containsKey(role); | ||
} | ||
|
||
@Override | ||
public boolean remRole(Role role) { | ||
return Objects.nonNull(roles.remove(role)); | ||
} | ||
|
||
@Override | ||
public <T extends Customer> Optional<T> getRole(Role role, Class<T> expectedRole) { | ||
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 + "}"; | ||
} | ||
} |
28 changes: 28 additions & 0 deletions
28
role-object/src/main/java/com/iluwatar/roleobject/CustomerRole.java
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,28 @@ | ||
/* | ||
* The MIT License | ||
* Copyright © 2014-2019 Ilkka Seppälä | ||
* | ||
* Permission is hereby granted, free of charge, to any person obtaining a copy | ||
* of this software and associated documentation files (the "Software"), to deal | ||
* in the Software without restriction, including without limitation the rights | ||
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell | ||
* copies of the Software, and to permit persons to whom the Software is | ||
* furnished to do so, subject to the following conditions: | ||
* | ||
* The above copyright notice and this permission notice shall be included in | ||
* all copies or substantial portions of the Software. | ||
* | ||
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR | ||
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, | ||
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE | ||
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER | ||
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, | ||
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN | ||
* THE SOFTWARE. | ||
*/ | ||
package com.iluwatar.roleobject; | ||
|
||
/** | ||
* Key abstraction for segregated roles | ||
*/ | ||
public abstract class CustomerRole extends CustomerCore{} |
Oops, something went wrong.