Bridge design pattern implementation - java

I have created one example for bridge design pattern. is it correct way to implement this or there is something I missed it?
Scenario : there is abstraction class Home which have abstract method paint implement by concreate classes(Flat and Apartment) and paint is another abstract class which having abstract method of paint(to paint the house). and one enum for color pickup.
abstract class Home {
private String homeType;
private Paint paint;
public Home(String type, Paint paint) {
this.homeType = type;
this.paint = paint;
}
abstract void paintTheHome();
public String getHomeType() {
return homeType;
}
public Paint getPaint() {
return paint;
}
}
public class Flat extends Home{
public static final String Type="Flat";
public Flat(Paint paint) {
super(Type,paint);
}
#Override
void paintTheHome() {
getPaint().paint(this);
}
}
public class Apartment extends Home {
public static final String Type="Apartment";
Apartment(Paint paint){
super(Type,paint);
}
#Override
void paintTheHome() {
getPaint().paint(this);
}
}
public abstract class Paint {
private Color color;
private String brand;
public Paint(Color color, String brand) {
this.color=color;
this.brand = brand;
}
public Color getColor() {
return color;
}
public String getBrand() {
return brand;
}
abstract void paint(Home home);
}
public class AsianPaint extends Paint{
public static final String brand = "Asian Paint";
public AsianPaint(Color color) {
super(color,brand);
}
#Override
void paint(Home home) {
System.out.println("Painting Started for "+home.getHomeType());
System.out.println("Brand of Color"+this.getBrand());
System.out.println("Name of Color"+this.getColor());
System.out.println("painting Ended");
}
}
public class ShalimarPaint extends Paint{
public static final String brand = "Shalimar Paint";
public ShalimarPaint(Color color) {
super(color,brand);
}
#Override
void paint(Home home) {
System.out.println("Painting Started for "+home.getHomeType());
System.out.println("Brand of Color"+this.getBrand());
System.out.println("Name of Color"+this.getColor());
System.out.println("painting Ended");
}
}
public enum Color {
RED("Red"),
GREEN("Green"),
BLUE("Blue"),
WHITE("White"),
YELLOW("Yellow");
String colorName;
Color(String string) {
this.colorName = string;
}
String getColor(){
return colorName;
}
}
public class client {
public static void main(String[] args) {
Home home = new Apartment(new AsianPaint(Color.RED));
home.paintTheHome();
home = new Flat(new ShalimarPaint(Color.GREEN));
home.paintTheHome();
}
}

Related

Restrain the type while inheriting

I created a java project to apply my GraphTheory course and enhance my java skills.
In this project :
I created a class Sommet<S>(Vertex in English) with an attribute Id with a generic type called <S>.
I created a class Arc<S>(Edge in English) with two attributes Sommet(Vertex).
I created a class EnsembleArc which is an HashSet of Arc
I also created a class ArcValue which inherit from Arc and have an int attribute Valeur(Value in English)
Here everything is fine and I dont have any problem.
But then I created a class EnsembleArcValue which inherit from EnsembleArc because every method from EnsembleArc will be useful to EnsembleArcValue.
But I also want EnsembleArcValue to be an HashSet of ArcValue (and I dont want an Arc which is not an ArcValue). And with the inheritance EnsembleArcValue is able to have an "simple" Arc in his Set.
So my question after all this explanation is :
Is there a way for EnsembleArcValue to inherit from EnsembleArc but will only accept an ArcValue in his Set.
Here is an image of The UML Project
I hope it will help to understand my problem (dont look at the bottom).
Here is the code :
public class Sommet<S>
{
//attributes
private S id;
public Sommet(S s)
{
setId(s);
}
public S getId()
{
return id;
}
public void setId(S s)
{
assert s!= null: "Objet null passé en paramètre";
id = s;
}
#SuppressWarnings("unchecked")
#Override
public boolean equals(Object obj)
{
boolean callback;
if(obj.getClass()!=getClass())
{
callback=false;
}
else
{
if(((Sommet<S>)obj).getId().equals(getId()))
{
callback=true;
}
else
{
callback=false;
}
}
return callback;
}
#Override
public int hashCode()
{
return getId().hashCode();
}
#Override
public String toString()
{
return getId().toString();
}
}
public class Arc<S>
{
private Sommet<S> depart;
private Sommet<S> arrivee;
public Arc(Sommet<S> dep, Sommet<S> arr)
{
setDepart(dep);
setArrivee(arr);
}
#Override
public String toString()
{
String str="("+getDepart().getId()+","+getArrivee().getId()+")";
return str;
}
public Sommet<S> getDepart()
{
return depart;
}
public Sommet<S> getArrivee()
{
return arrivee;
}
public void setDepart(Sommet<S> depart)
{
this.depart = depart;
}
public void setArrivee(Sommet<S> arrivee)
{
this.arrivee = arrivee;
}
#SuppressWarnings("unchecked")
#Override
public boolean equals(Object obj)
{
boolean callback;
if(obj.getClass()!=getClass())
{
callback=false;
}
else
{
if(((Arc<S>)obj).getDepart().equals(getDepart())&&((Arc<S>)obj).getArrivee().equals(getArrivee()))
{
callback=true;
}
else
{
callback=false;
}
}
return callback;
}
#Override
public int hashCode()
{
return getArrivee().hashCode()+getDepart().hashCode();
}
}
public class ArcValue<S,V> extends Arc<S>
{
private V valeur;
public ArcValue (Sommet<S> depart, Sommet<S> arrivee, V valeur)
{
super(arrivee,depart);
this.valeur=valeur;
}
public V getValeur()
{
return valeur;
}
}
import java.util.HashSet;
public class Ensemble<E> extends HashSet<E> implements Cloneable
{
private static final long serialVersionUID = -4354387895748449845L;
public Ensemble ()
{
super();
}
public Ensemble (Ensemble<E> ensemble)
{
for (E e : ensemble)
{
add(e);
}
}
public String toString()
{
StringBuffer str=new StringBuffer("{");
for(E e: this)
{
str=str.append(e.toString()+",");
}
str.setCharAt(str.length()-1, '}');
return str.toString();
}
#SuppressWarnings("unchecked")
#Override
public Ensemble<E> clone()
{
return (Ensemble<E>)super.clone();
}
}
public class EnsembleArc<S> extends Ensemble<Arc<S>>
{
public EnsembleArc(Ensemble<Arc<S>> ensemble)
{
super(ensemble);
}
public EnsembleArc()
{
super();
}
private static final long serialVersionUID = -4099925554493145279L;
public EnsembleSommet<S> listSucc(Sommet<S> sommet)
{
EnsembleSommet<S> XSucc=new EnsembleSommet<S>();
for (Arc<S> arc : this)
{
if (arc.getDepart()==sommet)
{
XSucc.add(arc.getArrivee());
}
}
return XSucc;
}
public EnsembleSommet<S> listPred(Sommet<S> sommet)
{
EnsembleSommet<S> XPred=new EnsembleSommet<S>();
for (Arc<S> arc : this)
{
if (arc.getArrivee()==sommet)
{
XPred.add(arc.getDepart());
}
}
return XPred;
}
public void add(Sommet<S> depart,Sommet<S>arrivee)
{
add(new Arc<S>(depart,arrivee));
}
#Override
public EnsembleArc<S> clone ()
{
return (EnsembleArc<S>)super.clone();
}
}
//import java.util.Collection;
public class EnsembleArcValues<S,V> extends EnsembleArc<S> //implements Collection<ArcValue<S,V>>
{
//TODO faire en sorte que ensembleArcValués ne contienne que des ArcsValue
private static final long serialVersionUID = -7163498825360866323L;
}
And you'll need this one to :
public class EnsembleSommet<S> extends Ensemble<Sommet<S>>
{
public EnsembleSommet()
{
super();
}
public EnsembleSommet(EnsembleSommet<S> ensemble)
{
super(ensemble);
}
private static final long serialVersionUID = 7278825382690341067L;
#Override
public EnsembleSommet<S> clone ()
{
return (EnsembleSommet<S>)super.clone();
}
public Sommet<S> firstSommet()
{
#SuppressWarnings("unchecked")
Sommet<S>[] tab=new Sommet[size()];
return toArray(tab)[0];
}
}
The only way you can achieve this is to make the type of Arc you want part of your generic deceleration. Rename your existing EnsembleArc to AbstractEnsembleArc and change it's generic decleration from < S > to < S, T extends Arc< S > > i.e.:
public abstract class AbstractEnsembleArc<S, T extends Arc<S>> extends Ensemble<T> {
// PUT ALL YOUR LOGIC CURRENTLY IN EnsembleArc HERE
}
Now create a new Class Called EnsembleArc and extend the new abstract class you've added, this new class will work identically to your existing EnsembleArc and class decleration should now look like:
public class EnsembleArc<S> extends AbstractEnsembleArc<S, Arc<S>> {
}
Finally have EnsembleArcValues extend the Abstract class instead of EnsembleArc so that you can declare that it should only accepts ArcValue and not simple Arc, do that like this:
public class EnsembleArcValues<S, V> extends AbstractEnsembleArc<S, ArcValue<S, V>> {
}

How to auto call method in class with initializing object of this class? (java)

public class Fruit {
public String name;
public double juiceAmount;
public Color color;
}
public class Orange extends Fruit {
public String name = "Orange";
public double juiceAmount = 0.3 * 250;
public Color color = Color.ORANGE;
public void setN(){
super.name = this.name;
}
}
I want to call setN method automatically after initializing object of Orange class!! tnx for help and sorry for bad English :))
You could just put it in a default constructor like this:
public Orange() {
this.setN();
}
public class Orange extends Fruit {
public String name = "Orange";
public double juiceAmount = 0.3 * 250;
public Color color = Color.ORANGE;
public Orange() {
this.setN();
}
public void setN(){
super.name = this.name;
}
}

On reload of page, mvp4g history mechanism fails

I have implemented a history mechanism for my mvp4g project. When I traverse through the pages, I can see the url also getting changed. But on reload of any page other than home page, always home page gets displayed instead of the desired page?
This is my implementation:
#History(type = HistoryConverterType.SIMPLE)
public class CustomHistoryConverter implements HistoryConverter<AppEventBus> {
private CustomEventBus eventBus;
#Override
public void convertFromToken(String historyName, String param, CustomEventBus eventBus) {
this.eventBus = eventBus;
eventBus.dispatch(historyName, param);
}
public String convertToToken(String eventName, String name) {
return name;
}
public String convertToToken(String eventName) {
return eventName;
}
public String convertToToken(String eventName, String name, String type) {
return name;
}
public boolean isCrawlable() {
return false;
}
}
and event bus related code :
#Events(startPresenter=PageOnePresenter.class,historyOnStart=true)
public interface CustomEventBus extends EventBusWithLookup {
#Start
#Event(handlers = PageOnePresenter.class)
void start();
#InitHistory
#Event(handlers = PageOnePresenter.class)
void init();
#Event(handlers = PageTwoPresenter.class, name = "page2", historyConverter = CustomHistoryConverter.class)
void getPageTwo();
#Event(handlers = PageThreePresenter.class, name = "page3", historyConverter=CustomHistoryConverter.class)
void getPageThree();
#Event(handlers=PageOnePresenter.class, name = "page1", historyConverter=CustomHistoryConverter.class)
void getPageOne();
#Event(handlers=PageOnePresenter.class)
void setPageTwo(HistoryPageTwoView view);
#Event(handlers=PageOnePresenter.class)
void setPageThree(HistoryPageThreeView view);
}
The HistoryConverter needs to be improved.
In fact, that the event has no parameter, you should return an empty string. Update the HistoryConverter that it looks like that:
#History(type = HistoryConverterType.SIMPLE)
public class CustomHistoryConverter implements HistoryConverter<AppEventBus> {
private CustomEventBus eventBus;
#Override
public void convertFromToken(String historyName, String param, CustomEventBus eventBus) {
this.eventBus = eventBus;
// TODO handle the param in cases where you have more than one parameter
eventBus.dispatch(historyName, param);
}
public String convertToToken(String eventName, String name) {
return name;
}
public String convertToToken(String eventName) {
return "";
}
public String convertToToken(String eventName, String name, String type) {
return name - "-!-" type;
}
public boolean isCrawlable() {
return false;
}
}
Hope that helps.

user defined enum with abstract methods decompiled as abstract class cannot be extended by any other class

I am trying to learn Enum when I came to know that when enums are decompiled they are final implicitly so cannot be extended by any other class but when any abstract method is added it asks for implementation of that method and decompiled it as abstract class so my question is that in this case it must allow this user defined enum to be extended by any other regular class.
below is my code which i have done on research purpose.
Vehicle.java
public enum Vehicle
{
car("car"), Bike;
private String value;
Vehicle(String value) {
this.value = value;
}
Vehicle() {
}
public String getValue() {
return value;
}
public void setValue(String value) {
this.value = value;
}
}
decompiled as:
public final class Vehicle extends java.lang.Enum<Vehicle> {
public static final Vehicle car;
public static final Vehicle Bike;
public static Vehicle[] values();
public static Vehicle valueOf(java.lang.String);
public java.lang.String getValue();
public void setValue(java.lang.String);
static {};
}
City.java
public enum City {
Nagpur("np") {
#Override
void show() {
// TODO Auto-generated method stub
}
};
abstract void show();
private String value;
City(String value) {
this.value = value;
}
City() {
}
public String getValue() {
return value;
}
public void setValue(String value) {
this.value = value;
}
}
decompiled as:
public abstract class City extends java.lang.Enum<City> {
public static final City Nagpur;
public static City[] values();
public static City valueOf(java.lang.String);
abstract void show();
public java.lang.String getValue();
public void setValue(java.lang.String);
City(java.lang.String, int, java.lang.String, City$1);
static {};
}
I have tried to recreate the scenario using regular classes which is working fine. below is the code.
Enum.java
public abstract class Enum<T extends Enum<T>> {
}
2.Vehicle.java
public abstract class Vehicle extends Enum<Vehicle> {
private String name;
Vehicle vehicle=new Vehicle() {
#Override
public void show() {
// TODO Auto-generated method stub
}
};
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public abstract void show();
}
3.Car.java
public class Car extends Vehicle {
#Override
public void show() {
// TODO Auto-generated method stub
}
}
Sorry for the long code and bad indention but I am really confused why user defined enums cannot be extended even after decompiling as abstract classes.
Thanks in advance for any help.
we cannot extend these enums because their constructors are private.

Why is "instanceof" not working?

I'm using the Java instanceof but it doesn't seem to be working.
I have three java classes that extend a Hero class.
The Hero.java class:
public abstract class Hero {
protected int health;
public Hero() {
}
}
The other three classes:
public class Archer extends Hero {
public Archer() {
}
}
public class Mage extends Hero {
public Mage() {
}
}
public class Warrior extends Hero {
public Warrior() {
}
}
I have this main class WelcomeScreen.java
public class WelcomeScreen {
private Archer archer;
private Mage mage;
private Warrior warrior;
private Hero hero;
public WelcomeScreen() {
// choose a hero (archer/mage/warrior)
hero = archer;
new Game(hero);
}
public static void main(String args[]) {
new WelcomeScreen();
}
}
that instantiates the Game.java class
public class Game {
public Game(Hero chosenHero) {
if (chosenHero instanceof Mage) {
System.out.println("you selected mage");
} else if (chosenHero instanceof Archer) {
System.out.println("you selected archer");
} else if (chosenHero instanceof Warrior) {
System.out.println("you selected warrior");
} else {
System.out.println("you selected NOTHING");
}
}
}
In Game.java, the code is meant to check whether chosenHero is an object of Archer.java, Warrior.java, or Mage.java, but I result with "you selected NOTHING". Why does instanceof fail to check if I already assigned it to Archer.java in the WelcomeScreen?
Because your constants are null. When you say,
private Archer archer;
it is equivalent to
private Archer archer = null;
Additionally, you have created three fields per instance. I think you wanted to do something like
private static final Hero archer = new Archer();
private static final Hero mage = new Mage();
private static final Hero warrior = new Warrior();
See also What does it mean to “program to an interface”?
Alternative solution: get rid of instanceof as it suggests a brittle rigid design, one that's easily broken. Instead try to use other more OOP-compliant solutions such as inheritance, or if complex, a Visitor Design Pattern.
For example, a simple inheritance structure could look something like:
public class WelcomeScreen {
public WelcomeScreen() {
// choose a hero (archer/mage/warrior)
Hero hero = new Archer();
new Game(hero);
}
public static void main(String args[]) {
new WelcomeScreen();
}
}
abstract class Hero {
protected int health;
// other shared fields such as String name,...
public Hero() {
}
public abstract String getType();
public int getHealth() {
return health;
}
}
class Archer extends Hero {
public static final String TYPE = "Archer";
public Archer() {
}
#Override
public String getType() {
return TYPE;
}
}
class Mage extends Hero {
public static final String TYPE = "Mage";
public Mage() {
}
#Override
public String getType() {
return TYPE;
}
}
class Warrior extends Hero {
public static final String TYPE = "Warrier";
public Warrior() {
}
#Override
public String getType() {
return TYPE;
}
}
class Game {
private Hero hero;
public Game(Hero chosenHero) {
this.hero = chosenHero;
System.out.println("You selected a hero of type " + hero.getType());
}
}

Categories

Resources