How does Decorator pattern work in Java? - 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'.

Related

How call subclass method by superclass object

I have 2 subclass extended from the same superclass, and 3 objects will be created and store into an array of the superclass. I am wondering how can I call a subclass method by a superclass object, I try to convert the data type from Ship to CruiseShip or CargoShip but it does not work. If anyone can help I will be appreciated that.
Here is the superclass:
public class Ship {
private String name;
private String year;
public Ship() {}
public Ship(String n,String y) {...}
public void setName() {...}
public void setYear() {...}
public void getName() {...}
public void getYear() {...}
}
These two subclass basically are there same.
public class CruiseShip extends Ship {
private int passenger;
public CruiseShip() {}
public CruiseShip() {...}
public void setPassenager() {...}
public int getPassenager() {...}
public Strting showInfo() {this.getName()...etc}
}
public class CargoShip extends Ship {
private int capacity;
public CargoShip() {}
public CargoShip() {...}
public void setCapacity() {...}
public int getCapacity() {...}
public Strting showInfo() {this.getName()...etc}
}
Here is the main method:
public class report {
public static void main(String[] args) {
Ship[] shipList new Ship[3];
for (int i=0;i<3;i++) {//using for loop to create 3 objects randomly and pass into array}
for (int i=0;i<3;i++) {
if (shipList[i] instanceof CruiseShip) {
((CruiseShip)shipList[i]).showInfo(); //This way is not work.
}
else {
((CargoShip)shipList[i]).showInfo(); //This way is not work.
}
Take a look at Polymorphisms and Late Bindig. Basically late binding says that the appropriate method to be executed is determined at runtime based on the actual type of the object. So
class Ship {
public String showInfo() {return "I'm a ship";}
}
class CruiseShip extends Ship {
public String showInfo() {return "I'm a cruiseShip";}
}
class CargoShip extends Ship {
public String showInfo() {return "I'm a cargoShip";}
}
class Main {
public static void main(String argv[]) {
Ship[] ships = new Ship[]{new Ship(), new CargoShip(), new CruiseShip()};
for (Ship ship: ships) {
System.out.println(ship.showInfo());
// I'm a ship
// I'm a cargoShip
// I'm a cruiseShip
}
}
}
I'm not sure about the question you are trying to ask,
but this may answer the question you did ask.
public abstract class Ship
{
public final boolean hoot()
{
return implementHoot();
}
protected abstract boolean implementHoot();
}
public class BlamShip
extends Ship
{
protected boolean implementHoot()
{
return true;
}
}
Subclass methods (overrides) are automatically called even if the reference is of type super-class. You don't have to do anything.

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();
}

Java abstract factory pattern

I'm trying to build a customer email generator in java using the abstract factory pattern. I understand how to use the factory method pattern; however, I'm a bit confused about the abstract factory pattern. I'm trying to generate an email based on customer type. Could you look at my code below and tell me if I'm using the abstract method correctly? Thank you
public abstract class EmailTemplate {
public abstract String getHeader();
public abstract String getBody();
public abstract String getFooter();
public String generateEmail(){
return getHeader()+"\n"+getBody()+"\n"+getFooter();
}
}
public interface EmailFactory {
EmailTemplate createEmail();
}
public class BusinessEmail extends EmailTemplate {
#Override
public String getHeader() {
return "Dear [business customer],";
}
#Override
public String getBody() {
return "Thank you for being our valued customer. We are so grateful for the pleasure of serving you and hope we met your expectations.";
}
#Override
public String getFooter() {
return "Best Regards," +
"[name]";
}
}
public interface EmailGeneratorFactory {
EmailTemplate createEmail();
}
public class BusinessFactory implements EmailGeneratorFactory {
#Override
public EmailTemplate createEmail() {
return new BusinessEmail();
}
}
public class EMailGenerationSystem {
private static EMailGenerationSystem EMailGenerationSystem = new EMailGenerationSystem();
private EMailGenerationSystem(){};
public static EMailGenerationSystem getInstance(){
return EMailGenerationSystem;
}
public EmailTemplate getEmail(EmailGeneratorFactory factory){
return factory.createEmail();
}
}

is it possible to check a variable with a list of method?

I want to pass a string into a series of method. These method will check whether the string have all properties needed. so, if the string didn't meet the requirement on one validator method, it will return false.
example :
input : "customerid=cu01","name=someone","phone=+628770xxxxx","address=somewhere","balance=500000"
output : true
another example :
"customerid=cu01","name=someone","address=somewhere","balance=200000"
output : false (no phone number)
Is it possible to create a list of validator class like this
List<Validator> val = new ArrayList<Validator>();
val.add(ValidatorA);
val.add(ValidatorB);
etc.
so i can check the string with that list of validator. i just want to know, is it possible to check a string with a list of validator like that? i'm doing this because it will be easier to add another validator if needed someday.
thanks
You could use the decorator pattern.
Take a look at this example I think it suits your usecase:
http://blog.decarufel.net/2009/09/using-decorator-or-wrapper-design.html
http://sourcemaking.com/design_patterns/decorator
public abstract class ValidationObject {
String description = "no particular";
public String getDescription(){
return description;
}
}
public class Account extends ValidationObject {
public Account(){
description = "account";
}
}
public class Book extends ValidationObject {
public Book () {
description = "book";
}
}
public abstract class ValidationObjectDecorator extends ValidationObject {
public abstract String getDescription();
}
public class ValidationOne extends ValidationObjectDecorator {
private ValidationObject account;
public ValidationOne (ValidationObject g) {
account = g;
}
#Override
public String getDescription() {
return account.getDescription() + "+ validationOneRan";
}
public void validateStuff() {
System.out.println("Big validation!");
}
}
We can add more method like "validateOtherStuff()" to each decorator without any limitations.
public class ValidationTwo extends ValidationObjectDecorator {
private ValidationObject book;
public ValidationTwo(ValidationObject g) {
book = g;
}
#Override
public String getDescription() {
return book.getDescription() + " ran validationTwo";
}
public void validationMethod() {
System.out.println("Big Validation!");
}
}
package designpatterns.decorator;
public class Main {
public static void main(String[] args) {
ValidationObject g1 = new Account();
System.out.println(g1.getDescription());
ValidationOne g2 = new Account(g1);
System.out.println(g2.getDescription());
ValidationTwo g3 = new Book(g2);
System.out.println(g3.getDescription());
}
}
Perhaps you can create an interface which will define a function such as "validate()", create implementations of this interface and then iterate over the list and apply the validate function.
Example:
public interface validator{
public boolean validate();
}
class validateUserName{
public boolean validate(){
return true;
}
}
class validatePhone{
public boolean validate(){
return false;
}
}
List<Validator> list = new ArrayList<Validator>();
list.add(new validPhone());
list.add(new validUserName());
for(Validator v : list)
v.validate();

Generics specific interface definition in Java

Is it possible to define following in Java:
public interface IGenericRepo<T> {
void add();
void delete();
void attach();
}
public interface IGenericRepo<Book> {
default String bookSpecificMethod(){
return "smthn";
}
}
public class NHGenericRepo<T> implements IGenericRepo<T>{
/* implementation */
}
public class NHUnitOfWork implements UnitOfWork{
#Autowired
public void setBookRepo(NHGenericRepo<Book> bookRepo) {
this.bookRepo= bookRepo;
}
public NHGenericRepo<Book> getBookRepo() {
return bookRepo;
}
private NHGenericRepo<Book> bookRepo;
}
And to be able somewhere in code to have:
{
#Autowired
public void setNhuw(NHUnitOfWork nhuw) {
this.nhuw = nhuw;
}
private NHUnitOfWork nhuw;
/**/
{
String st = this.nhuw.getBookRepo().bookSpecificMethod();
}
}
In .net this is possible by using Extension Method with "this IGenericRepo<Book>" as a first method parameter.
The closest you can come is:
public interface IBookGenericRepo extends IGenericRepo<Book> {
void BookSpecificMethod();
}

Categories

Resources