What is this the name of this Java state-based design pattern? - java

At my work, we have surveys, and one survey involves multiple steps. I work in automation, so I design tests around the page-objects we create for these surveys. We call this particular survey a "flow" survey because it has multiple steps. So you can skip step1 (survey A), then complete or skip step 2 (survey B), then complete or skip step 3 (survey C). Naively, we could write a test that just has methods that look like this:
public void completeSurveyA() {
//...
}
public void skipSurveyB() {
//...
}
public void completeSurveyB() {
//...
}
public void skipSurveyC() {
//...
}
public void completeSurveyC() {
//...
}
You would use it like this
completeSurveyA();
skipSurveyB();
completeSurveyC();
However, that could be a problem because we might call completeSurveyB() before we call completeSurveyA(), call completeSurveyA twice, etc. and the test would break. To avoid this, I introduced a different approach where calling a method on surveyA would return a surveyB object, which would return a surveyC object.
public class SurveyFlow() {
public SurveyB completeSurveyA() {
//...
return new SurveyB();
}
private class SurveyB() {
public SurveyC skipSurveyB() {
//...
return new SurveyC();
}
public SurveyC completeSurveyB() {
//...
return new SurveyC();
}
private class SurveyC() {
public void skipSurveyC() {
//...
}
public void completeSurveyC() {
//...
}
}
}
}
You would use it like this
new SurveyFlow().completeSurveyA().skipSurveryB().completeSurveyC();
The pattern reminds me of a state machine because only certain methods are available to you in different states, but I'm wondering if there is a more specific name for this pattern.

According to the classes of your example, it's a FluentInterface:
Probably the most important thing to notice about this style is that the intent is to do something along the lines of an internal DomainSpecificLanguage. (...) The API is primarily designed to be readable and to flow.
It's not the builder pattern, because you're not building anything (i.e. you don't have a final build() method where data gathered in previous steps is used to create an instance).
It's not the state pattern either, because operations (skip() and complete() in this case) do not depend on the state of an object (actually steps don't have a state).
It would have been the state pattern if the whole survey had been modeled as an object with one method whose implementation depended on different states (in this case, the states would be the steps plus the action taken, i.e. surveyACompleted, surveyASkipped, surveyBCompleted, surveyBSkipped, etc, while the method would be something like nextStep()):
public class SurveyFlow {
private SurveyState state; // this represents the current step
public SurveyFlow(boolean skipFirst) {
this.state = skipFirst ? new SurveyASkipped() : new SurveyACompleted();
}
void setState(SurveyState state) {
this.state = state;
}
public void takeStep(boolean skipNext) { // takeStep operation delegated
// to the state (current step)
this.state.takeStep(skipNext, this); // "this" passed to the step so
// that it can switch to the
// next step if needed
}
}
The state would be polymorphically represented by each step of the SurveyFlow:
abstract class SurveyState {
protected abstract void takeStep(boolean skipNext, SurveyFlow survey);
}
Survey A states would be as follows:
class SurveyACompleted extends SurveyState {
protected void takeStep(boolean skipNext, SurveyFlow survey) {
// ...
survey.setState(skipNext ? new SurveyBSkipped() : new SurveyBCompleted());
}
}
class SurveyASkipped extends SurveyState {
protected void takeStep(boolean skipNext, SurveyFlow survey) {
// ...
survey.setState(skipNext ? new SurveyBSkipped() : new SurveyBCompleted());
}
}
Survey B states would be as follows:
class SurveyBCompleted extends SurveyState {
protected void takeStep(boolean skipNext, SurveyFlow survey) {
// ...
survey.setState(skipNext ? new SurveyCSkipped() : new SurveyCCompleted());
}
}
class SurveyBSkipped extends SurveyState {
protected void takeStep(boolean skipNext, SurveyFlow survey) {
// ...
survey.setState(skipNext ? new SurveyCSkipped() : new SurveyCCompleted());
}
}
For your example:
Complete Survey A
Skip Survey B
Complete Survey C
You could do:
SurveyFlow survey = new SurveyFlow(false); // will complete survey A
survey.takeStep(true); // completed survey A and will skip survey B
survey.takeStep(false); // skipped survey A and will complete survey C
survey.takeStep(true); // completed survey C
If survey C is the last step, then it can ignore the boolean argument and shouldn't set further steps.

This is in a way the State pattern, but does not completely adhere to the State pattern described by GoF, because you are not changing the state of a single object, but rather creating and returning a new object of different class which you use afterwards.
Actually, this resembles much more the Builder pattern, where the completeSurveyC() acts as a build or getResult method to build a Surway from multiple consisting pieces specified earlier.

Related

Which OOP design pattern to use for different actions on an object based on its field values?

I have entity in database, say, MonthPlan:
class MonthPlan {
private boolean approved;
// other fields
}
There is also REST interface, which accepts external requests based on which program changes entity instances. For example, request
class EditMonthPlanRequest {
private long amount;
// other fields
}
is used to change month plan amount.
What I need is to execute different actions on MonthPlan entity based on value of approved field. For example, code for mentioned request could be as following
MonthPlan plan = getPlan(...);
if (plan.isApproved()) {
// actions using data from EditMonthPlanRequest
} else {
// other actions using data from EditMonthPlanRequest
}
There would be 5-6 different requests each with exactly two variants of actions based on value of approved field of edited entity. What OOP design pattern can I use for such use case to write more concise code?
I do not think you need a design pattern in such a simple case. Each request will be processed by the corresponding method at Service layer.
In this scenario, the state pattern is more suitable.
State design pattern is used when an Object changes its behavior based on its internal state.
If we have to change behavior of an object based on its state, we can have a state variable in the Object and use if-else condition block to perform different actions based on the state. State pattern is used to provide a systematic and lose-coupled way to achieve this through Context and State implementations.
Try to implement based on your description:
public class StatePattern {
public static void main(String[] args) {
MonthPlan monthPlan = null; //= new MonthPlan(...)
StateContext stateContext = new StateContext();
if(monthPlan.isApproved()) {
stateContext.setState(new Approved());
}else {
stateContext.setState(new NotApproved());
}
}
}
class MonthPlan {
private boolean approved;
public boolean isApproved() {
return approved;
}
// other fields
}
interface State{
public void doAction(StateContext ctx);
}
class StateContext{
private State currentState;
public StateContext() {
//default Approved state, you can change if you want
currentState = new Approved();
}
public void setState(State state) {
currentState = state;
}
public void doAction() {
currentState.doAction(this);
}
}
class Approved implements State{
#Override
public void doAction(StateContext ctx) {
//actions using data from EditMonthPlanRequest
}
}
class NotApproved implements State{
#Override
public void doAction(StateContext ctx) {
//other actions using data from EditMonthPlanRequest
}
}
For this simple case, the Template Method pattern may apply:
abstract class AbstractRequest {
public void execute(...){
MonthPlan plan = getPlan(...);
if (plan.isApproved()) {
executeForApproved(plan);
} else {
executeForNonApproved(plan);
}
}
protected abstract void executeForApproved(MonthPlan plan);
protected abstract void executeForNonApproved(MonthPlan plan);
}
This way, you don't need to repeat the if statement and the getPlan(...) in each subclass:
class EditMonthPlanRequest extends AbstractRequest {
private long amount;
// other fields
protected void executeForApproved(MonthPlan plan){
...
}
protected void executeForNonApproved(MonthPlan plan){
...
}
}
If you want to do OOP, then replace conditionals with polymorphism.
In this example, it means splitting MonthPlan in two.
class ApprovedMonthPlan extends MonthPlan
class UnapprovedMonthPlan extends MonthPlan
Each class handles EditMonthPlanRequest in its own way.

Java - Use of Type-specifc Interfaces

Consider the following: say we have an IRestaurant and an IBooking interface.
We then have the following interface function:
interface IBooking {
void reserve(IRestaurant restaurant);
}
However, business requirements dictate a booking service in a country could make reservations to only restaurants in the same country. Then say we have in USA:
class USABooking implements IBooking { ... }
class USARestaurant implements IRestaurant { ... }
In this case, since reserve() in IBooking takes in any instance of IRestaurant, the USABooking implementation would be required to check the instance of the IRestaurant to see if it is an instance of a USARestaurant and then downcast. However, we could also do this as an alternative:
interface IBooking<R extends IRestaurant> {
void reserve(R restaurant);
}
class USABooking implements IBooking<USARestaurant> {
void reserve(USARestaurant restaurant) { ... }
}
Is this a recommended way to go about enforcing the type limitation? In other words, is this better than performing runtime checks on the restaurant instance types? The typing approach sounds good to me, but I just want to make sure it won't "blow up" the architecture and turn out to be a misuse or abuse, since there are other interfaces that also would require such limitations (e.g. ICuisine).
Here's another alternative since I don't understand why there are USABooking and USARestaurant classes:
Consider just having a Booking and Restaurant class, where Restaurant provides a getCountry() method. Separately, to avoid a proliferation of classes, a Booking instance might have something like a List<RestaurantBookingRule> - in this case there would be a single rule that checks the country of the Restaurant. For example:
public class Restaurant {
private final String country; // constructor omitted
public String getCountry() { return country; }
}
public interface RestaurantBookingRule {
public void validateRequest(Restaurant r); // throws exception if the rule is broken
}
public class RequiredCountry implements BookingRule {
private final String country; // constructor omitted
public void validateRequest(Restaurant r) {
if (!r.getCountry().equals(country))
throw ...
}
}
public class Booking {
private final List<RestaurantBookingRule> rules; // constructor omitted
public void reserve(Restaurant r) {
rules.forEach(r -> r.validateRequest(r));
...
}
}
then:
Restaurant r1 = new Restaurant("USA");
Restaurant r2 = new Restaurant("CAN");
Booking usaBooking = new Booking(List.of(new RequriedCountry("USA"));
usaBooking.reserve(r1); // ok
usaBooking.reserve(r2); // throws exception

How to create a new object based on interface implementation

Firstly, I believe my question is badly worded but don't really understand how to phrase it.
I have a starting interface that is being implemented by a number of classes. What I want to do is to see if there is a way to create a new object such that I am being passed the generic interface, then based on the method .getClass().getSimpleName(), create a new object based on that string.
Is the only way to create a switch case statement? As the number of implementing classes are too many (about 100 or so).
Reference code:
public interface MyInterface {
public void someMethod();
}
then I would have my implementing classes:
public class MyClass1 implements MyInterface {
public void someMethod() { //statements }
}
public class MyClass2 implements MyInterface {
public void someMethod() { //statements }
}
public class MyClass3 implements MyInterface {
public void someMethod() { //statements }
}
What I want to have in the end is another class which is passed an argument of type MyInterface, get the simple name from that and create a new instance of MyClassX based on that simple name.
public class AnotherClass {
public void someMethod(MyInterface interface) {
if (interface == null) {
System.err.println("Invalid reference!");
System.exit(-1);
} else {
String interfaceName = interface.getClass().getSimpleName();
/**
* This is where my problem is!
*/
MyInterface newInterface = new <interfaceName> // where interfaceName would be MyClass1 or 2 or 3...
}
}
}
Any help is highly appreciated!
You can use reflection for this:
public void someMethod(MyInterface myInterface) {
Class<MyInterface> cl = myInterface.getClass();
MyInteface realImplementationObject = cl.newInstance(); // handle exceptions in try/catch block
}
This is a common problem with many solutions. When I face it, I never use reflection because it is difficult to maintain if it is part of a big project.
Typically this problem comes when you have to build an object based on a user selection. You can try a Decorator pattern for that. So, instead of building a different object for each option. You can build a single object adding functionality depending on a selection. For instance:
// you have
Pizza defaultPizza = new BoringPizza();
// user add some ingredients
Pizza commonPizza = new WithCheese(defaultPizza);
// more interesting pizza
Pizza myFavorite = new WithMushroom(commonPizza);
// and so on ...
// then, when the user checks the ingredients, he will see what he ordered:
pizza.ingredients();
// this should show cheese, mushroom, etc.
under the hood:
class WithMushroom implements Pizza {
private final Pizza decorated;
public WithMushroom(Pizza decorated) {
this.decorated = decorated;
}
#Override
public Lizt<String> ingredients() {
List<String> pizzaIngredients = this.decorated.ingredients();
// add the new ingredient
pizzaIngredients.add("Mushroom");
// return the ingredients with the new one
return pizzaIngredients;
}
}
The point is that you are not creating an object for each option. Instead, you create a single object with the required functionality. And each decorator encapsulates a single functionality.

Design Pattern - Fat adapter

We've implemented the adapter design pattern whose job is the following:
Act as a liaison between service and data access layers.
Convert raw data (from data source, internal or external) to domain specific data. Do necessary validation and massaging.
Sometimes, making the DAO calls may depend on data not readily available from input parameters or additional service calls may need to be made based on input data. In other words, the adapter can't always do a 1:1 mapping between the service and the DAO. It may map the same call from service to different DAO calls based on the input parameters.
Item #3 is starting to worry me as the adapters are becoming more complicated than I'd originally imagined. I'm not aware of a design pattern to trim down an adapter. Is there one? Suggestions?
You've used what I like to call the "swiss army knife" pattern.
Point 1 is broker pattern (or similar)
Point 2 is adapter pattern (or similar)
Point 3 is content based routing (or similar)
Best practice says you should break up your class into at least 3 classes, one for each concern.
Instead of using an adapter or a full Repository(CRUD operations), i would use an IReader interface for reading and visitor pattern for insert update delete, so you can separate domain logic from infraestructure(persistance) details, Here is the idea:
public class MyBusinessObject : IAcceptBusinessVisitor, IAcceptMyBusinessIdVisitor
{
private readonly string _id;
private string MyPrivateProp { get; set; }
//Fully encapsulated object
public MyBusinessObject(string id, string myPrivateProp)
{
_id = id;
MyPrivateProp = myPrivateProp;
}
public void UpdateMyProp(string newProp)
{
if (string.IsNullOrWhiteSpace(newProp)) throw new ArgumentNullException(nameof(newProp));
//Business rules ...
MyPrivateProp = newProp;
}
public void Accept(IMyBusinessObjectVisitor visitor)
{
if (visitor == null) throw new ArgumentNullException(nameof(visitor));
visitor.Visit(_id, MyPrivateProp);
}
public void Accept(IMyBusinessIdVisitor visitor)
{
if (visitor == null) throw new ArgumentNullException(nameof(visitor));
visitor.Visit(_id);
}
}
public interface IAcceptBusinessVisitor
{
void Accept(IMyBusinessObjectVisitor visitor);
}
public interface IAcceptMyBusinessIdVisitor
{
void Accept(IMyBusinessIdVisitor visitor);
}
public interface IMyBusinessObjectVisitor
{
void Visit(string id, string prop);
}
public interface IMyBusinessIdVisitor
{
void Visit(string id);
}
public class SavePersistanceVitor : IMyBusinessObjectVisitor
{
public void Visit(string id, string prop)
{
//Save to Database
}
}
public class UpdatePersistanceVitor : IMyBusinessObjectVisitor
{
public void Visit(string id, string prop)
{
//Update to Database
}
}
public class DeleteVitor : IMyBusinessIdVisitor
{
public void Visit(string id)
{
//Delete in Database
}
}
Here for Reading:
public interface IMyBusinessObjectReader
{
MyBusinessObject Read(string id);
}
class MyBusinessObjectReaderFromDb : IMyBusinessObjectReader
{
public MyBusinessObject Read(string id)
{
//Read from database
string myPrivateProp = "";
return new MyBusinessObject(id, myPrivateProp);
}
}
the next step could be adding generics for reading and the visitors. In this case you end up having little tiny classes and gain flexibility and the benefits of solid principles like single responsability, interface segregation, etc. So you can create a rich encapsulated domain and extend its functionality with some desing principles.
Regards!

Java interface : Calling an implementation class based on object types

I have an interface and its 2 implementations say :
public interface ObjectProcessor {
public void process(List<String> objectNames);
}
public CarImpl implements ObjectProcessor {
#override
public void process(List<String> carNames){
//car logic
} }
public VanImpl implements ObjectProcessor {
#override
public void process(List<String> vanNames){
//van logic
}
}
Now the caller who uses this interface looks like :
public void caller(VehicleType vehicleType, List<String> vehicleNames ) {
ObjectProcessor processor = null ;
if (VehicleType == VehicleType.CAR) {
processor = new CarImpl();
processor.process(vehicleNames);
}
}
VehicleType being an ENUM
This works fine. But is there anyway I can call an interface dynamically without
adding if statements. In the future if I am supporting another vehicle , I need to add an if statement along with a new implementation for the interface . How can I avoid this?
Overwrite abstract factory method in enum like this.
public enum VehicleType {
Car {
#Override
public ObjectProcessor createImpl() {
return new CarImpl();
}
},
Van {
#Override
public ObjectProcessor createImpl() {
return new VanImpl();
}
};
public abstract ObjectProcessor createImpl();
}
public void caller(VehicleType vehicleType, List<String> vehicleNames ) {
ObjectProcessor processor = vehicleType.createImpl();
processor.process(vehicleNames);
}
VechicleType combines enumeration with factory.
Or you can wirte all logics in enum like this.
public enum VehicleType {
Car {
#Override
public ObjectProcessor createImpl() {
return new ObjectProcessor() {
#Override
public void process(List<String> objectNames) {
// car logic
}
};
}
},
Van {
#Override
public ObjectProcessor createImpl() {
return new ObjectProcessor() {
#Override
public void process(List<String> objectNames) {
// van logic
}
};
}
};
public abstract ObjectProcessor createImpl();
}
In this case you don't need implementation classes (CarImpl, VanImpl, ...) any more.
Use Factory pattern. Here are some benefit from using it: http://javarevisited.blogspot.com/2011/12/factory-design-pattern-java-example.html#ixzz3ueUdV947
1) Factory method design pattern decouples the calling class from the target class, which result in less coupled and highly cohesive code?
2) Factory pattern in Java enables the subclasses to provide extended version of an object, because creating an object inside factory is more flexible than creating an object directly in the client. Since client is working on interface level any time you can enhance the implementation and return from Factory.
3) Another benefit of using Factory design pattern in Java is that it encourages consistency in Code since every time object is created using Factory rather than using different constructor at different client side.
4) Code written using Factory design pattern in Java is also easy to debug and troubleshoot because you have a centralized method for object creation and every client is getting object from same place
What you're basically implementing is a Factory pattern like proposed in the other answers. But in the end you will have to write an 'if' or 'switch' statement to select to correct implementation (or strategy) for your enum value. But like you mentioned yourself you'd have to extend this selection pattern whenever you add or remove an enum value. You can circumvent this by using a map like so:
public class ProcessorSelector {
private final Map<VehicleType, ObjectProcessor> processors;
public ProcessorSelector(Map<VehicleType, ObjectProcessor> processors) {
this.processors = processors;
}
public void process(VehicleType type, List<String> input) {
processors.get(type).process(input);
}
}
You can than configure your ProcessorSelector by passing a map with all the processor implementations mapped to the correct enum value (notice I used guava's ImmutableMap to conveniently construct the hashmap:
new ProcessorSelector(ImmutableMap.of(
VehicleType.CAR, new CarImpl(),
VehicleType.VAN, new VanImpl());
You'll never have to change your ProcessorSelector again, only the construction/configuration of the class. In fact you could say we just implemented the strategy pattern here. These selector classes are very common and if you feel you are implementing them quite often you could even use a more generic implementation, I recently described this in a blogpost: https://hansnuttin.wordpress.com/2015/12/03/functionselector/

Categories

Resources