I have the following class hierarchy:
public enum Bonus{
FP,
PRECOIL,
//some ohter types
};
public interface Generator{
public Object generate();
};
public class DateGenerator implements Generator{
public String queryString;
public Integer order;
//GET, SET
public Date generate(){
//implementation
}
};
public class BonusEnumGenerator implements Generator{
public Date bonusAppliedDate;
public String description;
//GET, SET
public Bonus generate(){
//implementation
}
}
So I need to put those params for generating the objects into a generalized Object.
Is it considered good if I create the class, say GeneratorParams and put all the params for all Generator's implementations. In my particular case I would have:
public class GeneratorParams{
public String queryString;
public Integer order;
public Date bonusAppliedDate;
public String description;
}
What's annoying me is that I put params which don't relate to each other in the same object. Is it good?
Why do I want to put all the params into a single object?
Beucase I want to write more generalized code. In that case I would have:
public interface Generator{
public Object generate();
public void applyParams(GeneratorParams params);
};
and applyParams method would be implemented for each type of Generator.
So I could write something like this:
Generator g = GeneratorPrototypeFactory.createGenerator(TypeId typeId);
GeneratorParams p;
//Getting params
g.applyParams(p);
Object generated = g.generate();
How can I solve that in more appropriate way?
simply make GeneratorParams an abstract class and move any common (in Date and BonusEnum generator) parameter to that:
public abstract class GeneratorParams {
public String commonParam;
//GET, SET
}
then add two sub-class:
public class DateGeneratorParams extends GeneratorParams {
public String queryString;
public Integer order;
// GET, SET
}
public class BonusEnumGeneratorParams implements GeneratorParams {
public Date bonusAppliedDate;
public String description;
// GET, SET
}
now implement appropriate applyParam in DateGenerator and BonusEnumGenerator:
public class DateGenerator implements Generator {
public String queryString;
public Integer order;
//GET, SET
public Date generate(){
//implementation
}
#Override
public void applyParams(GeneratorParams params) throws InvalidParamException {
if(!(params instanceof DateGeneratorParams))
throw new InvalidParamException();
else
// assign values
}
}
and
public class BonusEnumGenerator implements Generator {
public Date bonusAppliedDate;
public String description;
//GET, SET
public Bonus generate() {
//implementation
}
public void applyParams(GeneratorParams params) throws InvalidParamException {
if(!(params instanceof BonusEnumGeneratorParams))
throw new InvalidParamException();
else
// assign values
}
}
Related
I have these classes:
enum Brand {
FORD, FERRARI, TESLA, RENAULT;
}
public class Car {
Brand brand;
String plate;
...
}
//getters and setters
Imagine that for some reason, I need to make Car a superclass for two new classes: CombustionCar and ElectricCar. One of the new requierements is that ElectricCar's brand attribute must be always TESLA value and not any of the other ones values.
I've thougth some solutions:
I could keep Brand attr on superclass Car, and make ElectricCar constructor to set TESLA brand. But this way could allow me to set a new Brand after creating the object
public class ElectricCar extends Car {
public ElectricCar(...){
super(Brand.TESLA, ...);
}
ElectricCar ec = new ElectricCar(...);
ec.setBrand(Brand.FORD);
I can take Brand attr out from superclass and set it on both subclasses, but setting it in ElectricCar as a class attribute with a final so anyone would be able to set a new value
public class ElectricCar extends Car {
public static final Brand brand = Brand.TESLA;
...
}
public class CombustionCar extends Car {
private Brand brand;
...
}
Avoid inheritance and use composition, but with this I wont be able to use, for example, a List which contain both:
public class ElectricCar {
private Car car;
private Brand brand = Brand.TESLA;//with no setter
...
}
public class CombustionCar {
private Car car;
private Brand brand;
...
}
I'm asking for the most elegant and manteinable solution, I think any of them would be nice to resolve my problem.
Your first solution is incorrect given that you required a non editable BRAND for an electric car.
Your second solution just doesn't work at all excepted if you override both getter and setter of brand field to use your static field, which is not "elegant and mantainable"
Your third solution doesn't make use of object oriented concept.
A simple solution I would use is to let the field brand and its getter in Car superclass, but I'd only define the setter in the CombustionCar class.
Alternatively, if you extend your model, you could create an intermediate abstract superclass "FreeBrandCar" which implements the setter.
Solution with the setter in CombustionCar
abstract public class Car {
protected String brand;
protected Car(final String b) {
this.brand = b;
}
public String getBrand() {
return this.brand;
}
}
public class ElectricCar extends Car {
public ElectricCar() {
super("Tesla");
}
}
public class CombustionCar extends Car {
public CombustionCar(final String b) {
super(b);
}
public void setBrand(final String b) {
this.brand = b;
}
}
Solution with an intermediate class
abstract public class Car {
protected String brand;
protected Car(final String b) {
this.brand = b;
}
public String getBrand() {
return this.brand;
}
}
abstract public class FreeBrandCar extends Car {
public FreeBrandCar (final String b) {
super(b);
}
public void setBrand(final String b) {
this.brand = b;
}
}
public class ElectricCar extends Car {
public ElectricCar() {
super("Tesla");
}
}
public class CombustionCar extends FreeBrandCar {
public CombustionCar(final String b) {
super(b);
}
}
It respects your requirements :
public void test() {
ElectricCar ec = new ElectricCar();
ec.setBrand("..."): // Doesn't compile
CombustionCar cc = new CombustionCar("Ford"); // OK
cc.setBrand("Fiat"); // OK
Arrays.asList(ec, cc)
.stream()
.forEach(car -> System.out.println(car.getBrand())); // prints Tesla and Fiat
}
I am having two java class as below,
public class Class1{
private Object actionObject;
public Object getActionObject() {
return actionObject;
}
public void setActionObject(Object actionObject) {
this.actionObject = actionObject;
}
}
Second class
public class Class2 {
private Long id;
private int idver;
private int valueDate;
}
There are two statement as below,
Class1 deserializedValue = (Class1) event.getDeserializedValue();
Class2.class.isAssignableFrom(deserializedValue.getActionObject().getClass());
I want to mock the second statement
Class2.class.isAssignableFrom(deserializedValue.getActionObject().getClass());
how can i do this?
For testing purposes you can use a strategy pattern. You just need an interface or an abstract class with two different implementations. One of them is the mock implementation, something like this:
public interface EventStrategy {
// More methods...
boolean isAssignableFrom(final Object object);
}
public class MyEvent implements EventStrategy {
public boolean isAssignableFrom(final Object object) {
return Class2.class.isAssignableFrom(object.getClass());
}
}
public class MockEvent implements EventStrategy {
public boolean isAssignableFrom(final Object object) {
return true;
}
}
Method 1: traditional getter/setter
Toyota class:
public class ToyotaCar implements Serializable {
private static final long serialVersionUID = 2011932556974180375L;
private int miles;
public void addMiles(int miles){
this.miles = miles;
}
public int getMiles(){
return miles;
}
}
Human class:
public class Human implements Serializable {
private static final long serialVersionUID = 1748193556974180375L;
private ToyotaCar car;
public void setCar(ToyotaCar car){
this.car = car;
}
public int getCar(){
return car;
}
public void addCarMiles(int num){
getCar().addMiles(num);
}
}
Method 2: "other"
Toyota class: -same as above toyota class-
Additional containerHandler class:
public enum HumanContentsContainer {
CAR{
#Override public Object getContainer(){
return new ToyotaCar();
}
},
HOUSE;
public Object getContainer(){ //because cannot be static enum constant as every human has different items
return null;
}
}
Human class:
public class Human implements Serializable {
private static final long serialVersionUID = 1748193556974180375L;
private HashMap<HumanContentsContainer, Object> contents;
public void setContents(){
for (HumanContentsContainer c : HumanContentsContainer.values()){
contents.put(c, c.getContainer());
}
}
public HashMap<HumanContentsContainer, Object> getContents(){
return contents;
}
public void addCarMiles(int num){
//TODO how to replicate this: getCar().addMiles(num);???
}
//TODO i dont want to use the below method because whats the point of creating a whole container handler if im just going to use a traditional getter again?
//public ToyotaCar getCar(){
// return (ToyotaCar) contents.get(HumanContentsContainer.CAR);
// }
}
So how do I replicate the getCar().addMiles(x) method using a traditional getter without actually creating a getter?
Please note I also don't want to do this (below code): Because again, not worth it over a getter then:
public void addCarMiles(int num){
((ToytotaCar)contents.get(HumanContentsContainer.CAR).addMiles(num);
}
Looking for some easy kind of usage like:
human.getContentsThatIsIntanceOf(ToyotaCar).addMiles(1);
But don't know what getContentsThatIsInstanceOf would look like
I would go with:
public class Human implements Serializable {
private static final long serialVersionUID = 1748193556974180375L;
private ToyotaCar car;
public void setCar(ToyotaCar car){
this.car = car;
}
public int getCar(){
return car;
}
public void addCarMiles(int num){
getCar().addMiles(num);
}
public Map<HumanContentsContainer, Object> getContents(){
Map<HumanContentsContainer, Object>map = new HashMap();
map.put(CAR,this.car );
//same for all the shoes and clothes and whatever the Human has
}
public void setContents(){
for (HumanContentsContainer c : HumanContentsContainer.values()){
switch (c){
case CAR:{
this.car=c.getContainer();
}
}
//and so on
}
}
}
Edit
If you need to have a dynamic set of capabilities, I would suggest that you indeed keep the map of objects, and get rid of the ‘addCarMiles‘ method, as it implies that every human has a car.
I would implement public method on human ‘performCommand(CapabilityType, CapabilityCommand)‘ where the command will receive the capability and perform the operation on it. You may check out the Command Pattern tutorials.
Edit 2:
If all you want is to create a getter which will return dynamic type, you can use generics.
import java.io.Serializable;
import java.util.HashMap;
import java.util.NoSuchElementException;
public class Human implements Serializable {
private static final long serialVersionUID = 1748193556974180375L;
private HashMap<Class, Object> contents;
public void setContents(){
for (HumanContentsContainer c : HumanContentsContainer.values()){
contents.put(c.getContainer().getClass(), c.getContainer());
}
}
public HashMap<Class, Object> getContents(){
return contents;
}
public <T> T getContentsThatIsIntanceOf(Class<T> type){
Object object = contents.get(type);
if (object==null){
throw new NoSuchElementException("No such element: "+type.getName());
}
return type.cast(object);
}
public void usageExample(){
this.getContentsThatIsIntanceOf(ToyotaCar.class).addMiles(10);
}
}
I'm trying to prepare an interface i want to implement for Datamodel-Classes.Therefor i want to use an enum inside the interface so i know i need to implement it later.
Example:
public interface MyModelInterface {
public enum Field;
public Object get(Field field);
public void set(Field field, Object value);
}
The expected implementation:
public class MyModel implements MyModelInterface {
public enum Field {
ID("id"),
Name1("Name1"),
Name2("Name2");
private String field;
private Field(String field) {
this.field = field;
}
}
public Object get(Field field) {
//...
}
public void set(Field field, Object value){
//...
}
public static void main(String[] args) {
MyModel myModel = new MyModel();
System.out.println(myModel.get(MyModel.Field.ID));
System.out.println(myModel.get(MyModel.Field.Name1));
}
}
Since I don't know which fields the model will contain until I implement it.
I did some research and figured that enum can't be extended, so i am aware of that.
is there any way to archive this or any kind of workaround?
i don't want to use String Parameters on the getter/setter Methods to avoid using wrong values.
Thanks in advance for any suggestion.
Update:
So this is what worked for me: Splitting the interface/class in three parts, including an abstract class:
Interface:
public interface MyModelInterface<E extends Enum<E>> {
public Object get(E field);
public void set(E field, Object value);
}
Abstract Class:
public abstract class MyAbstractModel<E extends Enum<E>> implements MyModelInterface<E>{
protected final EnumMap<E, Object> fields;
public MyAbstractModel(Class<E> enumKlazz) {
fields = new EnumMap<>(enumKlazz);
}
#Override
public Object get(E field) {
return fields.get(field);
}
#Override
public void set(E field, Object value) {
this.fields.put(field, value);
}
}
Class(where i actually archive my goal):
public class MyModel extends MyAbstractModel<MyModel.Field> {
public MyModel() {
super(MyModel.Field.class);
}
public enum Field {
ID("ID"),
Name1("NAME1"),
Name2("NAME2"),
Age("AGE"),
;
private final String field;
private Field(String field) {
this.field = field;
}
public String getName() {
return field;
}
}
public static void main(String[] args) {
MyModel myModel = new MyModel();
System.out.println(myModel.get(Field.Name1));
}
}
Interface fields are static and final implicitly.
What you could do is to have an interface method returning Enum<?>, and your classes implementing it.
For instance:
interface Foo {
public Enum<?> getEnum();
}
class Bar implements Foo {
enum Blah {
INSTANCE;
}
public Enum<?> getEnum() {
return Blah.INSTANCE;
}
}
Edit
Not completely sure I understand your question update, but here's a solution that will de-couple returning a specific enum instance from an enum, by means of two interfaces.
The example is self-contained in a Main class.
public class Main {
public static void main(String[] args) {
System.out.println(new Bar().getEnumField().name());
}
static interface IHasEnum {
public Enum<? extends IMyEnum> getEnumField();
}
static interface IMyEnum {
public Enum<? extends IMyEnum> getField();
}
static class Bar implements IHasEnum {
enum Blah implements IMyEnum {
DEFAULT_INSTANCE,
THE_FIELD;
public Enum<? extends IMyEnum> getField() {
return THE_FIELD;
}
}
public Enum<? extends IMyEnum> getEnumField() {
return Blah.DEFAULT_INSTANCE.getField();
}
}
}
Output
THE_FIELD
Note
The trick here is to add a "default" instance to the enum (DEFAULT_INSTANCE), so the getField method is an instance method, hence overriding the one declared in the IMyEnum interface.
Again, not entirely sure this addresses your issue.
What you are describing is an EnumMap<E, T> - which functions like an array, with that same get-
public class MyModelBase<E extends Enum<E>> {
private final Class<E> enumKlazz;
private final EnumMap<E, Object> fields;
public MyModelBase(Class<E> enumKlazz) {
this.enumKlazz = enumKlazz;
fields = new EnumMpa<>(enumKlazz);
}
public Object get(E field) {
return fields.get(field);
}
public void set(E field, Object value) {
fields.put(field, value);
}
}
enum UserField { id, surname, name, age };
MyModelBase<UserField> userModel = new MyModelBase<>(UserField.class);
userModel.set(UserField.surname, "X");
Because of type erasure the enum map needs the class. Above the enum class is also stored as field, as some static Enum methods need the enum class. For iterating, and so on.
Java generics will be the best solution.
Lets assume, you don't know the contents of the Field as mentioned.
Create a generic interface like this:
public interface MyModelInterface<T> {
public T get();
}
Then create a class Field like this:
public class Field {
private String id;
private String name1;
private String name2;
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getName1() {
return name1;
}
public void setName1(String name1) {
this.name1 = name1;
}
public String getName2() {
return name2;
}
public void setName2(String name2) {
this.name2 = name2;
}
}
and then your model class will look like
public class MyModel implements MyModelInterface<Field> {
#Override
public Field get() {
Field field = new Field();
field.setId("ID");
field.setName1("Name1");
field.setName2("Name2");
return field;
}
public static void main(String[] args) {
MyModel myModel = new MyModel();
System.out.println(myModel.get().getId());
System.out.println(myModel.get().getName1());
System.out.println(myModel.get().getName2());
}
}
Lets say you have a particular enum called Field:
public enum Field {
ALBUM,
DESCRIPTION
}
And another enum called:
public enum Operator {
CONTAINS,
EQUALS,
LESS_THAN,
GREATER_THAN
}
And you have a corresponding Java interface called Music
public interface Music {
String getAlbum();
String getDescription();
}
Which the implementation looks liks this:
public class MusicImpl implements Music {
#Override
public String getYear() {
return Field.Year.toString();
}
#Override
public String getDescription() {
return Field.DESCRIPTION.toString();
}
#Override
public Object getField(Field field) {
Object myObject = field.getClass();
return myObject;
}
}
How would you use this API to implement the following two methods?
public class MyApp {
#Override
public List<Music> searchMusic(String query) {
// What to put in this?
}
#Override
public List<Music> filterMusic(Field field, Operator op, String query) {
// What to put in?
}
}