How should I approach wrapping the Composite pattern into the Builder pattern? - java

Lets say that I have a Composite set up as follows:
public abstract class Element {
//position, size, etc.
//element methods
//setters/getters
}
public class SimpleElement1 extends Element {
//...
}
public class SimpleElement2 extends Element {
//...
}
public class CompositeElement extends Element {
protected List<Element> childrenElements;
//methods to add/remove/get children
}
Now, how would I go about wrapping this Composite up into a Builder pattern, so that I can simplify client code by enabling it not to care (or care less) about the intricacies of how to link children to their Composite?

In your builder, add methods "startComposite" and "endComposite". These methods push a composite onto a stack and remove a composite from the stack. Messages to add elements always add to the top of stack.
builder.startComposite();
builder.simpleElement1();
builder.simpleElement2();
builder.endComposite();
builder.startComposite();
builder.simpleElement2();
builder.endComposite();
If your builder methods always return the builder, you can eliminate the repetition of the receiver:
builder.
startComposite().
simpleElement1().
simpleElement2().
endComposite().
startComposite().
simpleElement2().
endComposite();

Here is an example of a builder making an animal composite of different animal parts. You should be able to modify it for your particular application.
class BuilderDesignPattern{
public static void Main(string[] args)
{
Kid aKid = new Kid();
aKid.Name = "Elizabeth";
AnimalBuilder builderA = new MonkeyBuilder();
aKid.MakeAnimal(builderA);
builderA.aAnimal.ShowMe();
AnimalBuilder builderB = new KittenBuilder();
aKid.MakeAnimal(builderB);
builderB.aAnimal.ShowMe();
}
}
public abstract class AnimalBuilder
{
public Animal aAnimal;
public abstract void BuildAnimalHeader();
public abstract void BuildAnimalBody();
public abstract void BuildAnimalLeg();
public abstract void BuildAnimalArm();
public abstract void BuildAnimalTail();
}
public class MonkeyBuilder : AnimalBuilder
{
public MonkeyBuilder()
{
aAnimal = new Monkey();
}
public override void BuildAnimalHeader()
{
aAnimal.Head = "Moneky's Head has been built";
}
public override void BuildAnimalBody()
{
aAnimal.Body = "Moneky's Body has been built";
}
public override void BuildAnimalLeg()
{
aAnimal.Leg = "Moneky's Leg has been built";
}
public override void BuildAnimalArm()
{
aAnimal.Arm = "Moneky's Arm has been built";
}
public override void BuildAnimalTail()
{
aAnimal.Tail = "Moneky's Tail has been built";
}
}
public class KittenBuilder : AnimalBuilder
{
public KittenBuilder()
{
aAnimal = new Kitten();
}
public override void BuildAnimalHeader()
{
aAnimal.Head = "Kitten's Head has been built";
}
public override void BuildAnimalBody()
{
aAnimal.Body = "Kitten's Body has been built";
}
public override void BuildAnimalLeg()
{
aAnimal.Leg = "Kitten's Leg has been built";
}
public override void BuildAnimalArm()
{
aAnimal.Arm = "Kitten's Arm has been built";
}
public override void BuildAnimalTail()
{
aAnimal.Tail = "Kitten's Tail has been built";
}
}
public abstract class Animal
{
public BodyPart Head { get; set; }
public BodyPart Body { get; set; }
public BodyPart Leg { get; set; }
public BodyPart Arm { get; set; }
public BodyPart Tail { get; set; }
//helper method for demo the Polymorphism, so we can
//easily tell what type object it is from client.
public abstract void Eat();
//helper method for demo the result from client
public void ShowMe()
{
Console.WriteLine(Head);
Console.WriteLine(Body);
Console.WriteLine(Leg);
Console.WriteLine(Arm);
Console.WriteLine(Tail);
Eat();
}
}
public class Monkey : Animal
{
//helper method to show monkey's property for demo purpose
public override void Eat()
{
Console.WriteLine("Since I am Monkey, I like to eat banana");
}
}
public class Kitten : Animal
{
public override void Eat()
{
Console.WriteLine("Since I am Kitten, I like to eat kitten food");
}
}
public class Kid
{
public string Name { get; set; }
//construct process to build an animal object,
//after this process completed, a object
//will be consider as a ready to use object.
public void MakeAnimal(AnimalBuilder aAnimalBuilder)
{
aAnimalBuilder.BuildAnimalHeader();
aAnimalBuilder.BuildAnimalBody();
aAnimalBuilder.BuildAnimalLeg();
aAnimalBuilder.BuildAnimalArm();
aAnimalBuilder.BuildAnimalTail();
}
}
public class BodyPart{
String name= "";
public BodyPart(String name){
this.name=name;
}
}
}

Related

How to return a concrete implementation based on a variable(Enum/Object)

I was wondering how can I return a concrete implementation given a variable as argument in a function.
This is my test code
public interface Items {
String getName();
}
public class Car implements Items{
#Override
public String getName() {
return "Car";
}
public void drive(){
//To something
}
}
public class Shelf implements Items{
#Override
public String getName() {
return "Shelf";
}
public String getBooks(String bookName){
return bookName;
}
}
public enum Item {
CAR(Service::getCar),
TABLE(Service::getShelf),
;
Function<Service, ? extends Items> serviceFunction;
Item(Function<Service, ? extends Items> serviceFunction) {
this.serviceFunction = serviceFunction;
}
}
public class Service {
public Car getCar(){
return new Car();
}
public Shelf getShelf(){
return new Shelf();
}
public Items getItem(Item item){
return item.serviceFunction.apply(this);
}
public static void main(String[] args) {
Service service = new Service();
service.getItem(Item.CAR).getName();
// service.getItem(Item.CAR).drive(); // This is not valid.
}
}
So what I want is based on that enum I should be able to execute a set of functions related to that enum without passing the implementation identifier itself.
I know I can do this. And I will work but I was thinking of getting the concrete implementation without passing Class<T> klass.
public <T extends Items> T getItem(Item item, Class<T> klass){
return (T) item.serviceFunction.apply(this);
}
public static void main(String[] args) {
Service service = new Service();
service.getItem(Item.CAR, Car.class).drive();
}

Reflection in factory design patterns in Java or C#

I came across a term called reflection. It is a feature commonly used in factory design patterns. I had a hard time understanding the concept because I’m still learning how to program. How can reflection be used in factory design patterns in C# or Java? Can anyone give me a simple example, and show me your code that uses reflection to implement factory design patterns?
Microsoft provides this code example of reflection, but i don't see how this can be used in factory design patterns.
// Using GetType to obtain type information:
int i = 42;
System.Type type = i.GetType();
System.Console.WriteLine(type);
The Output is: System.Int32
I would never use reflection to implement Factory design pattern, unless there was a special case. The below code is a terrible way to implement the factory design pattern. But since you wanted to know "How" to use reflection for factory design pattern here's the example:
namespace NaiveFactory
{
public interface Shape
{
void Draw();
}
public class Circle : Shape
{
public void Draw() { Console.WriteLine("Drawing Circle"); }
}
public class Rectangle : Shape
{
public void Draw() { Console.WriteLine("Drawing Rectangle"); }
}
public class ShapeFactory
{
public static Shape GetShape<T>() where T : Shape
{
return Activator.CreateInstance<T>();
}
public static Shape GetShape(string shapeName)
{
var assembly = Assembly.GetExecutingAssembly();
var type = assembly.GetType(shapeName).FullName;
return (Shape) Activator.CreateInstanceFrom(assembly.Location, type).Unwrap();
}
}
class Program
{
static void Main(string[] args)
{
var shape = ShapeFactory.GetShape<Circle>();
var shape2 = ShapeFactory.GetShape("NaiveFactory.Rectangle");
shape.Draw();
shape2.Draw();
Console.ReadKey();
}
}
}
EDIT
As per suggestion from #AlexeiLevenkov, I have added something close to Dependency injection and instantiating the Shape objects using Constructor Injection as well as with a method:
namespace NaiveFactory
{
public interface IBoard
{
void InternalDraw(string str);
}
public class ConsoleBoard : IBoard
{
public void InternalDraw(string str) { Console.WriteLine(str); }
}
public class DebugBoard : IBoard
{
public void InternalDraw(string str) { Debug.WriteLine(str); }
}
public interface Shape
{
IBoard Board { get; set; }
void Draw();
void SetBoard(IBoard board);
}
public class Circle : Shape
{
public IBoard Board { get; set; }
public Circle()
{
}
public Circle(IBoard board)
{
Board = board;
}
public void Draw() { Board.InternalDraw("Drawing Circle"); }
public void SetBoard(IBoard board)
{
Board = board;
}
}
public class Rectangle : Shape
{
public IBoard Board { get; set; }
public Rectangle()
{
}
public Rectangle(IBoard board)
{
Board = board;
}
public void Draw() { Board.InternalDraw("Drawing Rectangle"); }
public void SetBoard(IBoard board)
{
Board = board;
}
}
public class ShapeFactory
{
private static Dictionary<Type, Type> _configurationData = new Dictionary<Type, Type>();
public static Shape GetShape<T>() where T : Shape
{
return Activator.CreateInstance<T>();
}
public static void ConfigureContainer<T, U>()
{
_configurationData.Add(typeof(T), typeof(U));
}
public static Shape GetShape_UsingConstructorInjection(string shapeName)
{
var assembly = Assembly.GetExecutingAssembly();
var type = assembly.GetType(shapeName);
var constructor = type.GetConstructor(_configurationData.Keys.ToArray());
if (constructor != null)
{
var parameters = constructor.GetParameters();
return (from parameter in parameters where _configurationData.Keys.Contains(parameter.ParameterType)
select Activator.CreateInstance(_configurationData[parameter.ParameterType]) into boardObj
select (Shape) Activator.CreateInstance(type, boardObj)).FirstOrDefault();
}
return null;
}
public static Shape GetShape_UsingSetBoardMethod(string shapeName)
{
var assembly = Assembly.GetExecutingAssembly();
var type = assembly.GetType(shapeName);
var shapeObj = (Shape) Activator.CreateInstance(type);
if (shapeObj != null)
{
shapeObj.SetBoard((IBoard) Activator.CreateInstance(_configurationData[typeof (IBoard)]));
return shapeObj;
}
return null;
}
}
class Program
{
static void Main(string[] args)
{
ShapeFactory.ConfigureContainer<IBoard, ConsoleBoard>();
var shape = ShapeFactory.GetShape_UsingSetBoardMethod("NaiveFactory.Circle");
var shape2 = ShapeFactory.GetShape_UsingConstructorInjection("NaiveFactory.Rectangle");
shape.Draw();
shape2.Draw();
Console.ReadKey();
}
}
}
Java version for this question
Code:
public class TestReflectionFactoryDesign {
public static void main(String[] args) throws Exception {
Person student = PersonFactory.getPersonWithFullQualifiedClassName("com.test.reflectionFactoryDesign.Student");
student.say();
Person teacher = PersonFactory.getPersonWithClass(Teacher.class);
teacher.say();
Person student2 = PersonFactory.getPersonWithName("student");
student2.say();
}
}
class Student implements Person {
#Override
public void say() {
System.out.println("I am a student");
}
}
class Teacher implements Person {
#Override
public void say() {
System.out.println("I am a teacher");
}
}
interface Person {
void say();
}
class PersonFactory {
// reflection, by full qualified class name
public static Person getPersonWithFullQualifiedClassName(String personType) throws Exception {
Class<?> personClass = Class.forName(personType);
return getPersonWithClass(personClass);
}
// reflection, by passing class object
public static Person getPersonWithClass(Class personClass) throws Exception {
return (Person) personClass.newInstance();
}
// no reflection, the ordinary way
public static Person getPersonWithName(String personType) {
if (personType.equalsIgnoreCase("STUDENT")) {
return new Student();
} else if (personType.equalsIgnoreCase("TEACHER")) {
return new Teacher();
}
return null;
}
}
Output:
I am a student
I am a teacher
I am a student

writing good abstract classes in java

I have the following need and please help me to write good and abstract class.
Different types of operations is needed based on the type
I have a abstract class,
abstract public class FileHelper{
//Template method
//This method defines a generic structure for parsing data
public void parseDataAndGenerateFile(String fileDownloadType)
{
createHeader(fileDownloadType);
generateFile();
}
//We have to write output in a excel file so this step will be same for all subclasses
public void createHeader(String fileDownloadType)
{
System.out.println('Creating HEADER in EXCEL');
}
public void generateFile(String fileDownloadType)
{
System.out.println('Output generated,writing to XLX');
}
}
public class ExcelDataParser extends FileHelper {
String fileDownloadType="";
}
public class TemplateMethodMain {
public static void main(String[] args) {
String fileDownloadType="expired";
ExcelDataParser csvDataParser=new ExcelDataParser();
csvDataParser.parseDataAndGenerateFile(fileDownloadType);
}
}
Please help me and correct me to have a good way of doing this.
If you want to use an abstract base class, you better should declare an abstract method String getDownloadType() in your abstract base class. These method must be overridden by the derived classes and the type could be fix in the derived class.
For example:
abstract public class FileHelper {
abstract String getFileDownloadType();
public void parseDataAndGenerateFile() {
createHeader();
generateFile();
}
public void createHeader() {
if ("expired".equals(getFileDownloadType())) {
} else {
}
}
public void generateFile() {
if ("expired".equals(getFileDownloadType())) {
} else {
}
}
}
public class ExcelDataParser extends FileHelper {
#Override
String getFileDownloadType() {
return "expired";
}
}
public class TemplateMethodMain {
public static void main(String[] args) {
ExcelDataParser csvDataParser = new ExcelDataParser();
csvDataParser.parseDataAndGenerateFile();
}
}
But if you don't need a class for every type, you also could make the type a variable inside a single class and passing the type to the contructor
For example:
public class CsvFileHelper {
private final String fileDownloadType;
public CsvFileHelper(String type) {
fileDownloadType = type;
}
public void parseDataAndGenerateFile() {
createHeader();
generateFile();
}
public void createHeader() {
if ("expired".equals(fileDownloadType)) {
} else {
}
}
public void generateFile() {
if ("expired".equals(fileDownloadType)) {
} else {
}
}
}
public class TemplateMethodMain {
public static void main(String[] args) {
CsvFileHelper csvDataParser = new CsvFileHelper("expired");
csvDataParser.parseDataAndGenerateFile();
}
}

Observer Pattern Class (JAVA)

I'm stuck on this assignment. I'm given an abstract Observer class with only 1 constructor in it, a constructor with parameters/arguments. (refer below)
public static void main(String[] args) {
PairOfNumbers numbers1 = new PairOfNumbers();
PairOfNumbers numbers2 = new PairOfNumbers();
SumObserver sum = new SumObserver(numbers1);
ProductObserver prod = new ProductObserver(numbers2);
MultiSubjectObserver m = new MultiSubjectObserver();
m.addSubject(numbers1);
m.addSubject(numbers2);
numbers1.setNumbers(20, 10);
numbers2.setNumbers(-10, 15);
}
class Subject {
private List<Observer> observers=new ArrayList<Observer>();
public void attachObserver(Observer observer) {
this.observers.add(observer);
}
public void detachObserver(Observer observer) {
this.observers.remove(observer);
}
public void notifyObservers() {
for (Observer observer: this.observers)
observer.update(this);
}
}
class PairOfNumbers extends Subject {
private double number1, number2;
public double getNumber1() { return this.number1; }
public double getNumber2() { return this.number2; }
public void setNumbers(double d1, double d2) {
this.number1=d1; this.number2=d2;
this.notifyObservers(); // don't forget to do this!
}
}
abstract class Observer {
public Observer(Subject subject) {
subject.attachObserver(this);
}
abstract public void update(Subject subject);
}
class SumObserver extends Observer {
public SumObserver(PairOfNumbers pair) {
super(pair);
}
public void update(Subject subject) {
PairOfNumbers numbers=(PairOfNumbers)subject;
System.out.println("New sum is: "+(numbers.getNumber1()+numbers.getNumber2()));
}
}
class ProductObserver extends Observer {
public ProductObserver(PairOfNumbers pair) {
super(pair);
}
public void update(Subject subject) {
PairOfNumbers numbers=(PairOfNumbers)subject;
System.out.println("New product is: "+(numbers.getNumber1()*numbers.getNumber2()));
}
}
Okay, now I'm suppose to create another class which inherits from the above class.
class MultiSubjectObserver extends Observer{
public MultiSubjectObserver(PairOfNumbers pair){
super(pair);
}
public void addSubject(PairOfNumbers pair){
pair.attachObserver(this);
}
public void update(Subject subject){
PairOfNumbers numbers=(PairOfNumbers)subject;
System.out.println("MultiSubjectObserver activated with numbers: " + (numbers.getNumber1())+", "+(numbers.getNumber2()));
}
}
Is there a way to create a constructor inside the MSO Class which requires no parameter/argument? For example
public MultiSubjectObserver(){
//enter code here
}
Please guide me on this one. Had been thinking for days. Thanks in advance! :D
The instruction is to: Modify the source code to handle any number of Subject objects per Observer.
Expected output:
New sum is: 30.0
MultiSubjectObserver activated with numbers: 20.0, 10.0
New product is: -150.0
MultiSubjectObserver activated with numbers: -10.0, 15.0
Yes you can do this, create a no-arg child class, but you still must call the arg-needing super constructor within the child constructor.
This:
class Child extends Super {
public Child() {
super(args_are_needed);
}
}
The tricky part would be -- what to pass into the super constructor in this default case? In your case this could be:
public MultiSubjectObserver(){
super(null);
}
Caveat: and this will lead to a NullPointerException when the super's constructor is called, due to the line, subject.attachObserver(this);, so no, you can't do this.
A better solution: make sure that MultiSubjectObserver does not extend from Observer!
Perhaps something like:
class MultiSubjectObserver {
private List<Observer> observerList = new ArrayList<Observer>();
public void addSubject(PairOfNumbers numbers1) {
observerList.add(new InnerObserver(numbers1));
}
private class InnerObserver extends Observer {
public InnerObserver(Subject subject) {
super(subject);
}
#Override
public void update(Subject subject) {
System.out.println("From multi-observer: " + subject);
}
}
}
But for this to work, you'd have to give PairOfNumbers a decent toString method, perhaps,
#Override
public String toString() {
return String.format("[%.4f, %.4f]", number1, number2);
}
Edit
Based on the output:
class MultiSubjectObserver {
private static final String FORMAT_STRING = "MultiSubjectObserver activated with numbers: %.1f, %.1f%n";
private List<Observer> observerList = new ArrayList<Observer>();
public void addSubject(PairOfNumbers numbers1) {
observerList.add(new InnerObserver(numbers1));
}
private class InnerObserver extends Observer {
public InnerObserver(Subject subject) {
super(subject);
}
#Override
public void update(Subject subject) {
System.out.printf(FORMAT_STRING, ((PairOfNumbers)subject).getNumber1(), ((PairOfNumbers)subject).getNumber1());
}
}
}
Although that casting is a bit skanky. I like the toString() version much better.

How does Decorator pattern work in Java?

I was trying to understand Decorator Pattern. Below is the code am trying to understand how it works.
public static void main(String[] args)
{
Room myRoom = new CurtainDecorator(new ColorDecorator(new SimpleRoom()));
System.out.println(myRoom.showRoom());
}
Below is my Concrete Class
public class SimpleRoom implements Room{
#Override
public String showRoom()
{
return "show room";
}
}
Below is my abstract Decorator class
public abstract class RoomDecorator implements Room{
public Room roomReference;
#Override
public String showRoom()
{
return roomReference.showRoom();
}
}
Below is my Decorator implementation1
public class ColorDecorator extends RoomDecorator{
#Override
public String showRoom()
{
return addColors(); //How does showRoom() method gets invoked here?
}
public ColorDecorator(Room room)
{
this.roomReference = room;
}
public String addColors()
{
return "Blue";
}
}
Below is my Decorator implementation 2
public class CurtainDecorator extends RoomDecorator{
public CurtainDecorator(Room room)
{
this.roomReference = room;
}
#Override
public String showRoom()
{
return this.roomReference.showRoom() + addCurtains(); //What will showRoom method invoke?
}
public String addCurtains()
{
return "Curtain";
}
}
Output is - BlueCurtain
My question are placed in the comment..
In the end you have:
CurtainDecorator(ref=ColorDecorator(ref=SimpleRoom)))
When you call showRoom from main, it calls the method of CurtainDecorator, which in turn first goes to it's reference (ColorDecorator in this case) that outputs 'Blue', then CurtainDecorator adds it's bit 'Curtain'.

Categories

Resources