Implementing the builder pattern - java

I have seen two popular methods of implementing the builder pattern:
// 1. The build() approach
Product p = builder.part1()
.part2()
.build();
// 2.The constructor approach
builder.part1()
.part2();
Product p = new Product(builder);
Which of these is preferable?

1st one is the way to go...
if you use the 2nd choice then doing this:
Product p = new Product(builder);
will add dependencies to the Product class..
that means the Product class needs now at least a constructor with the parameter builder

The question is a little vague, however in case you have a static builder class, effective java book of joshua bloch suggests a structure more like the first one with build method. It is a cleaner and safer way.
Product p= new Product.ProductBuilder("hw", "sw")
.version(30)
.mac("1234567")
.address("Fake address 1234")
.build();

I tend to use a combination of both of those examples.
I would define a builder class inside the Product class and give the product class a private constructor that takes a ProductBuilder.

These are two different approaches. Trades-off are different.
You must use and adapt a pattern according your needs and your context, not according a hard rule...
Using a builder like it :
Product p = new Product(builder);
allows to create your builder and to reuse it.
If you need to reuse the builder or to create the builder in another class, it is a good implementation. You open your API because you need it.
The drawbacks of the solution are a no straight way of creating your object.
About design quality and dependency, I think that it is a false problem.
Yes with a public constructor for Product, you create a public dependency between Product and builder and you expose the Product constructor.
But if in the Product constructor, you dispatch to the builder instance the task for constructing the Product, is the coupling will make the code less flexible ? Never. Besides, the real coupling is located in the Product construction since the builder uses mirrors properties to build the Product object. So, the real and strong coupling will stay whatever happens: these two classes must work together and must look like.
Using a builder like it :
Product p = builder.part1()
.part2()
.build();
doesn't allow to reuse builder but is more straight to use for your client of the class and it opens at the minimum the dependency between Builder to Product.
If you don't need to reuse the builder or to create the builder in another class, it's the best since you don't open your API in a useless way.
So, in the facts, both solutions are near.
I would use the solution with a constructor if I must reuse the builder or i need to create the builder in another class and i would use the solution without constructor if not needed.

Related

Up to what extent can you prevent modifying existing code when using design patterns?

I am taking a design patterns class in school, and have read through some chapters of Head First Design Patterns. What I'd like to find out is up to what extent can design patterns prevent rewriting of existing code.
Let us take Duck classes and FlyBehavior classes for example. I have in public static void main(String[] args) the following code:
Duck mallard = new MallardDuck(new FlyWithWings());
Am I right in saying that it is inevitable that you'll have to modify your main() method when you want to add a new strategy? In that way, you are modifying existing code, right? I am specifically referring to the part where a concrete strategy class is mentioned: new FlyWithWings().
If you implemented the factory method pattern in your code, you could prevent having a concrete class (FlyWithWings) from being mentioned at all:
public FlyBehavior returnBehavior(FlyBehaviorFactory factory, String behaviorType) {
return factory.getFlyBehavior(behaviorType);
}
And thus, have the following line of code:
Duck mallard = new MallardDuck(returnBehavior(flyFactory, "wings"));
This way, a certain portion of your program does not have to know about what FlyBehaviorFactory to use. Yet, your main() method will still have to specify certain parameters in the returnBehavior method in order to know what factory will create what strategy. Thus, am I right in saying that you'll still have to modify main() if I added a new FlyBehavior class, and wanted to add that as a parameter to returnBehavior()?
Can one improve this situation any further?
In the current example, you are hard-coding the parameters passed to your factory and are thus deciding the behavior at compile time.
Duck mallard = new MallardDuck(returnBehavior(flyFactory, "wings"));
This can be changed to plugin a particular behavior at runtime instead of compile time :
Duck mallard = new MallardDuck(returnBehavior(flyFactory, args[0]));
With the above change, you will never have to change your main method. Your factory can be written in a way that it throws an exception when a behavior recieved at runtime is not available :
if(behaviorType.equals("wings") {
//...create FlyWithWings
} else{
//throw an appropriate exception indicating that the behavior does not exist
}
That being said, it is inevitable to change code if a new behavior is introduced. Although, this change will be in one single place and as far behind in your application as possible, i.e your factory which is the whole point of factory in the first place. Also, when you create a new FlyBehavior, you are doing so by extending from an existing class. This is inline with the open-closed principle
What you are doing here is dependency injection, you are injecting the FlyBehaviour into Duck. Sometimes when using dependency injection like this you can have a chain of injections. For example if you wanted a speed strategy to be injection into FlyBehaviour you might have something like this.
Duck mallard = new MallardDuck(new FlyWithWings(new FastSpeed()));
It wouldn't be nice to have main and any other class that uses Duck to have to know about all of these classes and have to change everytime any of these did. A better solution would be to use a dependency injection container which is responsible for creating each of these classes. Then in main you can just call something like this
Duck mallard = (Duck) Container.get('Duck');
The container is responsible for creating all the instances needed for the injection. So to answer your question you will need to change your code when wanting a new strategy but at least this way it is only in one place instead of throughout your code which could be many files.

Java Design Patterns - Builder and Singleton

I am fairly new to Design Patterns in programming, and I am trying to learn them by creating recipes and a meal. There can be many recipes but only one meal.
Using Builder:
Create a Recipe, which will contain a name, ingredients, etc.
Using Singleton:
Instantiate my CurrentMeal, which should contain an ArrayList<Recipe>. I also should be able to access a Recipe inside my CurrentMeal.
While I believe I understand Builder, I am not sure I understand Singleton all that well. Am I approaching this problem in an appropriate manner? If not, any suggestions as to an approach to take would be greatly appreciated. Thanks in advance.
builder pattern:
Intent:
Separate the construction of a complex object from its representation so that the same construction process can create different representations.
Key points:
Builder pattern builds a complex object using simple objects and using a step by step approach
A Builder class builds the final object step by step. This builder is independent of other objects
Replacement to Factory method/Abstract Factory in this scenario : Too Many arguments to pass from client program to the Factory class that can be error prone
Some of the parameters might be optional unlike in Factory which forces to send all parameters
UML diagram:
Builder:
Abstract interface for creating objects (product).
ConcreteBuilder:
Provides implementation for Builder. It is an object able to construct other objects. Constructs and assembles parts to build the objects
Guidelines for Builder design pattern in Java
Make a static nested class called Builder inside the class whose object will be build by Builder
Builder class will have exactly same set of fields as original class
Builder class will expose method for adding ingredients. Each method will return same Builder object. Builder will be enriched with each method call.
Builder.build() method will copy all builder field values into actual class and return object of Item class
Item class (class for which we are creating Builder) should have private constructor to create its object from build() method and prevent outsider to access its constructor.
Refer to this journaldev article for more details.
Singleton pattern:
Intent:
Ensure a class has only one instance, and provide a global point of access to it.
Encapsulated "just-in-time initialization" or "initialization on first use"
singleton should be considered in below scenarios:
Ownership of the single instance cannot be reasonably assigned
Lazy initialization is desirable
Global access is not otherwise provided for
UML diagram:
Have a look at below SE question for more details:
What is an efficient way to implement a singleton pattern in Java?
The Singleton pattern allows you to share a single instance of an object. If you would like to share your CurrentMeal property, then you can of course encapsulate it in a Singleton, although I don't really see the point. It's not really what the pattern is designed for. You might use Singleton to implement a logging mechanism, for example.
The Builder pattern is well-suited to your application, as it allows different Recipe implementations to be constructed based on similar properties.

Need a way to define input arguments for constructor in interface

First of all, I know it isn't possible to define constructors in interfaces in Java. But somehow, I've run into a problem where I need something very similar. Maybe there is an easy solution for my case...
I have an interface:
public interface SomeObject {
/**
* Generate a xml representation of the object.
*/
public String generateXMLRepresentation();
}
This xml-representation of the object will be stored somewhere and later on it should be possible to construct a copy of the object using this xml-representation. My intial thought was to define a constructor which takes a String as input and let every implementation of SomeObject know how to handle it and how to construct the corresponding object.
How can I achieve this?
Edit: Either I wasn't clear enough about that or I think about it the wrong way but I think that Factory or Builder patterns won't work. I need something stronger where everyone can write a new implementation of SomeObject and is forced to implement an constructor which takes an xml string. To put it another way, I do not how many or which implementations of SomeObject exist and still, I'm relying on that every implementation knows how to construct itself from an xml-representation.
I believe for this you should use the Factory pattern, since we are talking about building up an object based on a string.
So you should have different static methods constructing different implementations for a given String.
public class ObjV1 implements SomeObject(){ // objects would simply extend interface
...
}
public class SomeObjectFactory{// factory would provide construction methods for different implementations of the interface
//Hide factory constructor, so we use it only as a singleton
private SomeObjectFactory(){
}
public static ObjV1 buildV1(String str){
ObjV1 obj = new ObjV1(); // note that we're using the noarg constructor
...
return obj;
}
}
If you want to have more control over the building process, you should give the Builder pattern a try
Some Design Patterns can help you to define a solution that can handle your current context. Both the Abstract Factory and the Builder pattern can help you.
I'd rather go with the Builder design pattern. You'll end up being able to construct from simple to complex objects based solely on that XML representation you have by implementing the proper logic.
I think you should consider separating the concern of xml serialisation from whatever concern your object is dealing with. Is knowledge of to and from xml really intrinsic to the domain of your class, or is it an orthogonal concern?
Have a look at http://x-stream.github.io/
If you do not want to use xstream itself, because you can't depend on the jar, or your xml form is particular to your project, at least look at what xstream does. You should be able to define a single strategy to (reflectively?) recurse an object structure and write out xml in the form you require, and a companion class to do the opposite.

builder pattern and limiting implicit object creation

If I use builder pattern that create some PRODUCT, i would, probably should want to limit the ability to create this PRODUCT by explicit way?
Because it is probably not good of users of my code would create PRODUCT like new PRODUCT().
I mean the users of my code my do not know about some builder.
So, should I make constructor of PRODUCT with as private? And then in the Builder I would use reflection to create the initial instance of the PRODUCT?
Does this approach make sense? Is it ok?
Or you set the constructor as protected, and create a builder in the same package, so it has access to it, or create static methods that might even use your builder implicitly.
If your ProductBuilder is able to create an instance of Product through reflection, then any other class can do the same.
I think, it's easier to add builder and product to the same namespace (package) and make the constructor package private. It has the same effect (invisible for classes outside the package) and keeps the code clean.
What you seem to be describing is called the Factory Pattern (rather than the builder pattern).
The simplest way to implement this is to make your constructor private and provide static factory methods on the Product class. This is the bare minimum implementation:
public class Product {
private Product() {}
public static Product create() {
return new Product();
}
}
There are plenty of classes in the JDK that follow this pattern, for example Integer.parseInt is static factory method the creates as Integer (although the constructor is not private)
Alternatively, you could create a separate Factory class in the same package as Product and give the Product constructor the default visibility.
You should avoid using reflection in general, unless you really need it. In this case you don't need it - keep things as simple as possible (but no simpler).

What is the difference between Factory and Strategy patterns?

Can any one explain the difference between factory and strategy patterns?
For me both are looking same other than an extra factory class (which create an object of product in factory patterns)
A factory pattern is a creational pattern. A strategy pattern is an operational pattern. Put another way, a factory pattern is used to create objects of a specific type. A strategy pattern is use to perform an operation (or set of operations) in a particular manner. In the classic example, a factory might create different types of Animals: Dog, Cat, Tiger, while a strategy pattern would perform particular actions, for example, Move; using Run, Walk, or Lope strategies.
In fact the two can be used together. For example, you may have a factory that creates your business objects. It may use different strategies based on the persistence medium. If your data is stored locally in XML it would use one strategy. If the data were remote in a different database, it would use another.
The strategy pattern allows you to polymorphically change behavior of a class.
The factory pattern allows you to encapsulate object creation.
Gary makes a great point. If you are using the principle of coding to abstractions rather than "concretions" then a lot of the patterns start looking like variations on a theme.
Just to add to what tvanfosson said, a lot of the patterns look the same as far as implementation. That is, a lot have you create an interface where perhaps there wasn't one before in your code, and then create a bunch of implementations of that interface. The difference is in their purpose and how they are used.
First of all a difference between simple factory and abstract factory must be made. The first one is a simple factory where you only have one class which acts as a factory for object creation, while in the latter you connect to an factory interface (which defines the method names) and then call the different factories that implement this interface which are supposed to have different implementations of the same method based on some criteria. For example, we have a ButtonCreationFactory interface, which is implemented by two factories, the first WindowsButtonCreationFactory (creates buttons with Windows look and feel) and the second LinuxButtonCreationFactory (creates buttons with Linux look and feel). So both these factories do have the same creation method with different implementations (algorithms). You can reference this in runtime based on the method that you type of button that you want.
For example if you want buttons with Linux look and feel:
ButtonCreationFactory myFactory = new LinuxButtonCreationFactory();
Button button1 = myFactory.createButton(...);
or if you want Windows buttons
ButtonCreationFactory myFactory = new WindowsButtonCreationFactory();
Button button1 = myFactory.createButton(...);
Exactly in this case, it results in a kind of strategy pattern, since it differentiates algorithms for doing some creation. However, it differs from it semantically because it is used for OBJECT CREATION rather than operational algorithms. So, basically with abstract factory you have object creation using different strategies, which makes it very similar to the strategy pattern. However the AbstractFactory is creational, while the Strategy pattern is operational. Implementation wise, they result to be the same.
The Factory ( method ) Pattern.
Create concrete instances only. Different arguments may result in different objects. It depends on the logic etc.
The Strategy Pattern.
Encapsulate the algorithm ( steps ) to perform an action. So you can change the strategy and use another algorithm.
While both look like very similar, the purpose is rather different, one purpose is to create the other is to perform an action.
So. If your Factory method is fixed, you may have it like this:
public Command getCommand( int operatingSystem ) {
switch( operatingSystem ) {
case UNIX :
case LINUX : return new UnixCommand();
case WINDOWS : return new WindowsCommand();
case OSX : return new OSXCommand();
}
}
But suppose your factory needs more advanced or dynamic creation. You may add to the factory method an strategy and change it without having to recompile, the strategy may change at runtime.
Factory (and FactoryMethod returned by Factory):
Creational pattern
Based on inheritance
Factory returns a Factory Method (interface) which in turn returns Concrete Object
You can substitute new Concrete Objects for interface and client (caller) should not be aware of all concrete implementations
Client always access interface only and you can hide object creation details in Factory method
Have a look at this wikipedia article and javarevisited article
Strategy pattern:
It's a behavioural pattern
It's based on delegation
It changes guts of the object by modifying method behaviour
It's used to switch between family of algorithms
It changes the behaviour of the object at run time
Example:
You can configure Discount strategy for a particular item ( AirFare ticket or ShoppingCart item). In this example, you will offer 25% discount to an item during July - December and No discount on the item during Jaunary - June.
Related posts:
Real World Example of the Strategy Pattern
Design Patterns: Factory vs Factory method vs Abstract Factory
To extend on what Oscar said and in reference to his code:
The getCommand is the Factory and the UnixCommand, WindowsCommand and OSXCommand classes are Strategies
Strategy pattern in simple terms is more of runtime creation of behaviour where you are not concerned with the implementing class. On the other had factory is runtime creation of concrete class instance and it is up to you to use any behaviour(method) exposed by the implemented interface.
Factory pattern is a creational pattern, which is created with specified properties(behaviour). while at run time after creation u cn't change it's properties(behaviour). so if u need different properties(behaviour) u have to delete the object and create new object with needed properties(behaviour). which is not gud.
while in case of strategy pattern u can change the properties(behaviour) at run time.
You cannot understand the difference simply by looking at the code or categorization. To grasp the GoF patterns correctly, look for their intents:
Strategy: "Define a family of algorithms, encapsulate each one, and make them interchangeable. Strategy lets the algorithm vary independently from clients that use it."
Factory Method: "Define an interface for creating an object, but let subclasses decide which class to instantiate. Factory Method lets a class defer instantiation to subclasses."
And here's an elaborate explanation about the intents and the differences between these two patterns: Difference between Factory Method and Strategy design patterns
The key difference between Factory Pattern and Strategy Pattern is where the operation is done. Factory Pattern does the operation on the created objects (the factory class done the job after creation), whereas Strategy Pattern does the operation on the context class itself.
To change a Factory Pattern to a Strategy Pattern, instead of returning the created object from the factory class, holding the object inside a context class, and creating a wrapper method inside the context class to do the operation instead of doing the operation directly from the created object.
While somebody may ask if we can do the operation on the created object, why do we still need to create a wrapper to do at context class? OK, the key thing is the operation. Strategy Pattern can alter the operation based on the strategy, and you don't need to alter the object, you can rely on the context object to do different operations instead of changing the object itself.
I may digress with Oscar in that his example of a Factory implementation is rather tightly coupled and very closed, no wonder your pick is Strategy pattern. A Factory implementation should not depend on any fixed number of specific classes being instantiated, For example:
public Command getCommand( int operatingSystem ) {
return commandTable.get(operatingSystem);
}
...
public class WindowsCommand implements Command {
...
static {
CommandTable.getInstance().registerCommand(WIN_COMMAND_ID, new WindowsCommand());
}
}
I guess the most appropriate criteria to choose one or another is mostly the terms you employ to name your classes and methods, taking into account we all should tend to program to interfaces and not to classes and also focus on the goal: we aim to determine which code will execute on runtime. That said, we can achieve the goal by using any of both patterns.
Strategy and Factory are different purposes. In strategy you have the approach defined, using this pattern you can interchange the behavior (algorithms). Coming to Factory there are lot of variations around. But the original pattern from GO4 states factory leaves creation of object to child class. Here with the factory you are replacing complete instance not the behavior you are interested in. By this you will be replacing complete system not the algorithm.
In brief:
Factory is for create multi object that has same behaviour but Strategy is for One Object that has different way to work.
Factory Pattern is about deciding which Object to create, but Strategy Pattern is about using the created object. For example, which strategy is to use can be decided by Factory Pattern

Categories

Resources