Java Design Patterns - Builder and Singleton - java

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.

Related

What exactly can we describe Factory Method of design pattern?

I am confused with the concept ? Is it just as simple as incorporating a static method to return the object instead of a constructor ? So that client doesn't need to change the code while we update the library or there is something more to it ?
The book Head First Design Patterns will be your definitive guide for Java. That is a great book. If you check out my answer to this Stack Overflow Question, you will be able to see my implementation for an ArbitraryPointFactory class in the Point Example code that uses the Factory Method pattern as well as how it differs from Abstract Factory pattern seen in the Point Factory class. Although this answer is presented with C# code samples, the design pattern language I am using to describe their usage, should warrant you an answer.
What you are thinking of in your question is not a design pattern at all. This static method that returns an object to encapsulate the instantiation, is known as the Simple Factory as seen in the Wiki page. The Factory Method pattern more or less abstracts the type being returned via an interface. This is typically done where the sole job of the factory method class is to control creation of the objects for one concrete class that implements the interface being returned. The Abstract Factory provides encapsulation for a group of related products. In my example I was showing for different types of points, however they could implement different interfaces and all use the same Abstract Factory.
The idea is that you are programming to interfaces, not implementations. True factories pull creation logic to a single location in your application and encapsulate the instantiation via interfaces.

Implementing the builder pattern

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.

Is Object deserialization a proper way to implement Prototype pattern in Java?

TL;DR
Can I use Java serialization/deserialization using Serializable interface, ObjectOutputStream and ObjectInputStream classes, and probably adding readObject and writeObject in the classes implementing Serializable as a valid implementation for Prototype pattern or not?
Note
This question is not to discuss if using copy constructor is better than serialization/deserialization or not.
I'm aware of the Prototype Pattern concept (from Wikipedia, emphasis mine):
The prototype pattern is a creational design pattern in software development. It is used when the type of objects to create is determined by a prototypical instance, which is cloned to produce new objects. This pattern is used to:
avoid subclasses of an object creator in the client application, like the abstract factory pattern does.
avoid the inherent cost of creating a new object in the standard way (e.g., using the 'new' keyword) when it is prohibitively expensive for a given application.
And from this Q/A: Examples of GoF Design Patterns in Java's core libraries, BalusC explains that prototype pattern in Java is implemented by Object#clone only if the class implements Cloneable interface (marker interface similar to Serializable to serialize/deserialize objects). The problem using this approach is noted in blog posts/related Q/As like these:
Copy Constructor versus Cloning
Java: recommended solution for deep cloning/copying an instance
So, another alternative is using a copy constructor to clone your objects (the DIY way), but this fails to implement the prototype pattern for the text I emphasized above:
avoid the inherent cost of creating a new object in the standard way (e.g., using the 'new' keyword)
AFAIK the only way to create an object without invoking its constructor is by deserialization, as noted in the example of the accepted answer of this question: How are constructors called during serialization and deserialization?
So, I'm just asking if using object deserialization through ObjectOutputStream (and knowing what you're doing, marking necessary fields as transient and understanding all the implications of this process) or a similar approach would be a proper implementation of Prototype Pattern.
Note: I don't think unmarshalling XML documents is a right implementation of this pattern because invokes the class constructor. Probably this also happens when unmarshalling JSON content as well.
People would advise using object constructor, and I would mind that option when working with simple objects. This question is more oriented to deep copying complex objects, where I may have 5 levels of objects to clone. For example:
//fields is an abbreviation for primitive type and String type fields
//that can vary between 1 and 20 (or more) declared fields in the class
//and all of them will be filled during application execution
class CustomerType {
//fields...
}
class Customer {
CustomerType customerType;
//fields
}
class Product {
//fields
}
class Order {
List<Product> productList;
Customer customer;
//fields
}
class InvoiceStatus {
//fields
}
class Invoice {
List<Order> orderList;
InvoiceStatus invoiceStatus;
//fields
}
//class to communicate invoice data for external systems
class InvoiceOutboundMessage {
List<Invoice> invoice;
//fields
}
Let's say, I want/need to copy a instance of InvoiceOutboundMessage. I don't think a copy constructor would apply in this case. IMO having a lot of copy constructors doesn't seem like a good design in this case.
Using Java object serialization directly is not quite the Prototype pattern, but serialization can be used to implement the pattern.
The Prototype pattern puts the responsibility of copying on the object to be copied. If you use serialization directly, the client needs to provide the deserialization and serialization code. If you own, or plan to write, all of the classes that are to be copied, it is easy to move the responsibility to those classes:
define a Prototype interface which extends Serializable and adds an instance method copy
define a concrete class PrototypeUtility with a static method copy that implements the serialization and deserialization in one place
define an abstract class AbstractPrototype that implements Prototype. Make its copy method delegate to PrototypeUtility.copy.
A class which needs to be a Prototype can either implement Prototype itself and use PrototypeUtility to do the work, or can just extend AbstractPrototype. By doing so it also advertises that it is safely Serializable.
If you don't own the classes whose instances are to be copied, you can't follow the Prototype pattern exactly, because you can't move the responsibility for copying to those classes. However, if those classes implement Serializable, you can still get the job done by using serialization directly.
Regarding copy constructors, those are a fine way to copy Java objects whose classes you know, but they don't meet the requirement that the Prototype pattern does that the client should not need to know the class of the object instance that it is copying. A client which doesn't know an instance's class but wants to use its copy constructor would have to use reflection to find a constructor whose only argument has the same class as the class it belongs to. That's ugly, and the client couldn't be sure that the constructor it found was a copy constructor. Implementing an interface addresses those issues cleanly.
Wikipedia's comment that the Prototype pattern avoids the cost of creating a new object seems misguided to me. (I see nothing about that in the Gang of Four description.) Wikipedia's example of an object that is expensive to create is an object which lists the occurrences of a word in a text, which of course are expensive to find. But it would be foolish to design your program so that the only way to get an instance of WordOccurrences was to actually analyze a text, especially if you then needed to copy that instance for some reason. Just give it a constructor with parameters that describe the entire state of the instance and assigns them to its fields, or a copy constructor.
So unless you're working with a third-party library that hides its reasonable constructors, forget about that performance canard. The important points of Prototype are that
it allows the client to copy an object instance without knowing its class, and
it accomplishes that goal without creating a hierarchy of factories, as meeting the same goal with the AbstractFactory pattern would.
I'm puzzled by this part of your requirements:
Note: I don't think unmarshalling XML documents is a right
implementation of this pattern because invokes the class constructor.
Probably this also happens when unmarshalling JSON content as well.
I understand that you might not want to implement a copy constructor, but you will always have a regular constructor. If this constructor is invoked by a library then what does it matter? Furthermore object creation in Java is cheap. I've used Jackson for marshalling/unmarshalling Java objects with great success. It is performant and has a number of awesome features that might be very helpful in your case. You could implement a deep copier as follows:
import com.fasterxml.jackson.databind.ObjectMapper;
public class MyCloner {
private ObjectMapper cloner; // with getter and setter
public <T> clone(T toClone){
String stringCopy = mapper.writeValueAsString(toClone);
T deepClone = mapper.readValue(stringCopy, toClone.getClass());
return deepClone;
}
}
Note that Jackson will work automatically with Beans (getter + setter pairs, no-arg constructor). For classes that break that pattern it needs additional configuration. One nice thing about this configuration is that it won't require you to edit your existing classes, so you can clone using JSON without any other part of your code knowing that JSON is being used.
Another reason I like this approach vs. serialization is it is more human debuggable (just look at the string to see what the data is). Additionally, there are tons of tools out there for working with JSON:
Online JSON formatter
Veiw JSON as HTML based webpage
Whereas tools for Java serialization isn't great.
One drawback to this approach is that by default duplicate references in the original object will be made unique in the copied object by default. Here is an example:
public class CloneTest {
public class MyObject { }
public class MyObjectContainer {
MyObject refA;
MyObject refB;
// Getters and Setters omitted
}
public static void runTest(){
MyCloner cloner = new MyCloner();
cloner.setCloner(new ObjectMapper());
MyObjectContainer container = new MyObjectContainer();
MyObject duplicateReference = new MyObject();
MyObjectContainer.setRefA(duplicateReference);
MyObjectContainer.setRefB(duplicateReference);
MyObjectContainer cloned = cloner.clone(container);
System.out.println(cloned.getRefA() == cloned.getRefB()); // Will print false
System.out.println(container.getRefA() == container.getRefB()); // Will print true
}
}
Given that there are several approaches to this problem each with their own pros and cons, I would claim there isn't a 'proper' way to implement the prototype pattern in Java. The right approach depends heavily on the environment you find yourself coding in. If you have constructors which do heavy computation (and can't circumvent them) then I suppose you don't have much option but to use Deserialization. Otherwise, I would prefer the JSON/XML approach. If external libraries weren't allowed and I could modify my beans, then I'd use Dave's approach.
Your question is really interesting Luiggi (I voted for it because the idea is great), it's a pitty you don't say what you are really concerned about. So I'll try to answer what I know and let you choose what you find arguable:
Advantages :
In terms of memory use, you will get a very good memory consumption by using serialization since it serializes your objects in binary format (and not in text as json or worse: xml). You may have to choose a strategy to keep your objects "pattern" in memory as long as you need it, and persist it in a "less used first persisted" strategy, or "first used first persisted"
Coding it is pretty direct. There are some rules to respect, but it you don't have many complex structures, this remains maintainable
No need for external libraries, this is pretty an advantage in institutions with strict security/legal rules (validations for each library to be used in a program)
If you don't need to maintain your objects between versions of the program/ versions of the JVM. You can profit from each JVM update as speed is a real concern for java programs, and it's very related to io operations (JMX, memory read/writes, nio, etc...). So there are big chances that new versions will have optimized io/memory usage/serialization algos and you will find you're writing/reading faster with no code change.
Disadvantages :
You loose all your prototypes if you change any object in the tree. Serialization works only with the same object definition
You need to deserialize an object to see what is inside it: as opposed to the prototype pattern that is 'self documenting' if you take it from a Spring / Guice configuration file. The binary objects saved to disk are pretty opaque
If you're planning to do a reusable library, you're imposing to your library users a pretty strict pattern (implementing Serializable on each object, or using transient for dields that are not serializable). In addition this constraints cannot be checked by the compiler, you have to run the program to see if there's something wrong (which might not be visible immediately if an object in the tree is null for the tests). Naturally, I'm comparing it to other prototyping technologies (Guice for example had the main feature of being compile time checked, Spring did it lately too)
I think it's all what comes to my mind for now, I'll add a comment if any new aspect raises suddenly :)
Naturally I don't know how fast is writing an object as bytes compared to invoking a constructor. The answer to this should be mass write/read tests
But the question is worth thinking.
There are cases where creating new object using copy constructor is different from creating new object "in a standard way". One example is explained in the Wikipedia link in your question. In that example, to create new WordOccurrences using the constructor WordOccurrences(text, word), we need to perform heavyweight computation. If we use copy constructor WordOccurrences(wordOccurences) instead, we can immediately get the result of that computation (in the Wikipedia, clone method is used, but the principle is the same).

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.

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