I have a couple of helper classes (? extends HelperBase) which only have public static methods. I would like to have something similar to what a factory is (with singleton support), but as there is no need for an instance, I am unsure which way to go best.
In the end, I would like to have something like:
enum HELPER_TYPE {
Type_A
}
abstract class HelperBase {
abstract void do();
static HelperBase getHelper(HELPER_TYPE type) {
// ...
}
}
class Helper1 extends HelperBase {
static void doImpl() {
// ... impl here
}
void do() {
doImpl();
}
}
// ... and then:
HelperBase helper = HelperBase.getHelper(HELPER_TYPE.Type_A);
helper.do();
Is there a better way ? Any suggestion would be appreciated.
enum HELPER_TYPE implements IHelper{
Type_A{
#Override
public void doSomething(){
}
},
Type_B{
#Override
public void doSomething(){
}
}
}
interface IHelper{
public void doSomething();
}
How about having an interface with required methods and having enum implement that?
Now you have polymorphic behavior among all helpers implementing IHelper interface.
So you can call them like HELPER_TYPE.Type_A.doSomething()
Related
My program takes data from different file types and inserts them into different DBs depending on the department which uploaded the file.
To accomplish this, I have a base abstract class AbstractHandler which has some methods which are unimplemented and some which are common to all children. Two types of abstract classes extend from this class, InputTypeAHandler, InputTypeBHandler, etc. and OutputTypeAHandler, OutputTypeBHandler, etc. These abstract classes also implement some more methods but not all.
I have concrete classes which I want to extend from these two types of classes and which will implement some more methods specific to every class. For example,
abstract class AbstractHandler {
public void method1() {
// ....
}
public abstract void method2();
public abstract void method3();
public abstract void method4();
}
abstract class InputTypeAHandler extends AbstractHandler {
#Override
public void method2() {
// ....
}
}
abstract class OutputTypeBHandler extends AbstractHandler {
#Override
public void method3() {
// ....
}
}
public class ConcreteHandler1 extends InputTypeAHandler, OutputTypeBHandler {
#Override
public void method4() {
// ....
}
}
public class ConcreteHandler2 extends InputTypeCHandler, OutputTypeAHandler {
#Override
public void method4() {
// ....
}
}
Since Java does not allow multiple inheritance, how do I do this?
You seem to implement some kind of conversion between any pair of A,B,C... types (perhaps formats?). If it is the case, the AbstractHandler probably has multiple responsibilities. Split its logic to part involving source format and part involving target format. You can inspire in converter pattern or GoF Bridge pattern.
I use lombok and the power of interfaces for this:
public class Test implements InputTypeAHandler,OutputTypeAHandler {
#Delegate
OutputTypeAHandlerImp outputTypeAHandlerImp = new OutputTypeAHandlerImp() {
#Override
String id() {
return "mellow";
}
};
#Delegate
InputTypeAHandlerImp inputTypeAHandler = new InputTypeAHandlerImp(){
#Override
String id() {
return "hello124";
}
};
}
public static abstract class OutputTypeAHandlerImp implements OutputTypeAHandler {
abstract String id();
#Override
public void write(String s) {
System.out.println(s);
}
}
public static abstract class InputTypeAHandlerImp implements InputTypeAHandler {
abstract String id();
#Override
public String read() {
return new Scanner(System.in).nextLine();
}
}
public interface InputTypeAHandler {
String read();
}
public interface OutputTypeAHandler{
void write(String s);
}
I can't wrap my head around it at the moment, maybe that's a stupid question but I give it a go.
Lets say I have these Classes:
class CellType1 {
public void doSomething(){
// does something ClassType1 specific
}
}
class CellType2 {
public void doSomething(){
// does something ClassType2 specific
}
}
class CellType3 {
public void doSomething(){
// does something ClassType3 specific
}
}
These classes share the same functions but the functions themselves work differently. Now I have this Class:
class Map<CellTypes>{
CellTypes cell;
//...
public void function(){
cell.doSomething();
}
//...
}
This Class' Generic Type will later be one of the three upper classes. And in this class I want to access the doSomething()-Function for this specific CellType-Object. I've tried doing
class Map<CellTypes extends CellType1, CellType2, CellType3> {
/*...*/
}
But this limits me to the function/s of CellType1.
How can I use the functions from different Classes in a Generic class?
Maybe someone has a better idea than me!
I hope this was understandable.
Thank you in advance.
EDIT:
I need to have my Class Map as a Generic Class, because I need to create different objects of map and pass them the CellType-class they need to be working with.
You can create an interface:
interface CellType {
public void doSomething();
}
And implement the interface like this:
class CellType1 implements CellType {
public void doSomething(){
// does something ClassType1 specific
}
}
class CellType2 implements CellType {
public void doSomething(){
// does something ClassType2 specific
}
}
class CellType3 implements CellType {
public void doSomething(){
// does something ClassType3 specific
}
}
Map class:
class Map<T extends CellType> {
T cell;
//...
public void function(){
cell.doSomething();
}
//...
}
public interface CanDoSomething {
public void doSomething();
}
Then all the other classes implement this interface. This works only if the method signature is the same in all cases.
interface CellType {
void doSomething();
}
class CellType1 implements CellType {
public void doSomething(){
//your logic
}
}
//similar implementation logic for CellType2 and CellType3
class Map {
private CellType cellType;
public Map(CellType cellType){
this.cellType = cellType;
}
public void someFunc(){
cellType.doSomething();
}
}
Hope this helps
I am not sure how am I suppose to go about my question. It is about Android can Instantiate Interface. I am trying to do in C#. Now I am pretty sure that the rules for both Java and C# is you can't create an Instance of abstract and Interface as being said.
But I would really like to know how Android does this practice.
In Android you can do this.
public interface Checkme{
void Test();
void Test2();
}
public void myFunc(Checkme my){
//do something
}
// Now this is the actual usage.
public void Start(){
myFunc(new Checkme(){
#Override
public void Test()
{
}
#Override
public void Test2()
{
}
});
}
Actually once you press Enter on new Checkme() You will automatically get the Override methods of the Interface. Like auto Implement method of an Interface in C#.
I hope my question make sense.
C# doesn't support anonymously auto-implemented interfaces because it has delegates:
public void Foo(Func<string> func, Action action) {}
// call it somewhere:
instance.Foo(() => "hello world", () => Console.WriteLine("hello world"));
With delegates you can fill the gap and it can be even more powerful than implementing interfaces with anonymous classes.
Learn more about delegates.
This is an Anonymous Class:
public void Start(){
myFunc(new Checkme() {
#Override
public void Test() {
}
#Override
public void Test2() {
}
});
}
An anonymous class is an unnamed class implemented inline.
You could also have done it using a Local Class, but those are rarely seen in the wild.
public void Start(){
class LocalCheckme implements Checkme {
#Override
public void Test() {
}
#Override
public void Test2() {
}
}
myFunc(new LocalCheckme());
}
These both have the advantage that they can use method parameters and variables directly, as long as they are (effectively) final.
As a third option, you could do it with an Inner Class.
private class InnerCheckme implements Checkme {
#Override
public void Test() {
}
#Override
public void Test2() {
}
}
public void Start(){
myFunc(new InnerCheckme());
}
An inner class cannot access method variables (obviously because it's outside the method), but can be used by multiple methods.
Any local values from the method can however be passed into the constructor and stored as fields of the inner class, to get the same behavior. Just requires a bit more code.
If the inner class doesn't need access to fields of the outer class, it can be declared static, making it a Static Nested Class.
So, all 3 ways above a very similar. The first two are just Java shorthands for the third, i.e. syntactic sugar implemented by the compiler.
C# can do the third one, so just do it that way for C#.
Of course, if the interface only has one method, using a Java lambda or C# delegate is much easier than Anonymous / Local / Inner classes.
If I understand correcly, you're defining a class that implements an interface, and when you specify that the class implements an interface, you want it to automatically add the interface's methods and properties.
If you've declared this:
public interface ISomeInterface
{
void DoSomething();
}
And then you add a class:
public class MyClass : ISomeInterface // <-- right-click
{
}
Right-click on the interface and Visual Studio will give you an option to implement the interface, and it will add all the interface's members to the class.
you mean something like this?
pulic interface Foo{
void DoSomething();
}
public class Bar : Foo {
public void DoSomething () {
//logic here
}
}
myFunc(new Checkme(){
#Override
public void Test()
{
}
#Override
public void Test2()
{
}
});
You're passing into myFunc() something that is called an anonymous class. When it says "new Checkme() { .... }", it is defining an anonymous implementation of the Checkme interface. So, it's not an instance of the interface itself, just an instance of a type that implements it.
In C# anonymously implemented classes for Interface are not auto generated just like in java, you need to follow the below procedure to workout.
public class MyClass {
public void someMethod (string id, IMyInterface _iMyInterface) {
string someResponse = "RESPONSE FOR " + id;
_iMyInterface.InterfaceResponse (someResponse);
}
}
public interface IMyInterface {
void InterfaceResponse (object data);
void InterfaceResponse2 (object data, string x);
}
public class MyInterfaceImplementor : IMyInterface {
private readonly Action<object> actionname;
private readonly Action<object, string> actionInterfaceResponse2;
public MyInterfaceImplementor (Action<object> InterfaceResponse) {
this.actionname = InterfaceResponse;
}
public MyInterfaceImplementor(Action<object> interfaceResponseMethod, Action<object, string> interfaceResponseMethod1) {
this.actionname = interfaceResponseMethod ?? throw new ArgumentNullException(nameof(interfaceResponseMethod));
this.actionInterfaceResponse2 = interfaceResponseMethod1 ?? throw new ArgumentNullException(nameof(interfaceResponseMethod1));
}
public void InterfaceResponse (object data) {
this.actionname (data);
}
public void InterfaceResponse2(object data, string x) {
this.actionInterfaceResponse2(data, x);
}
}
Gist Source : https://gist.github.com/pishangujeniya/4398db8b9374b081b0670ce746f34cbc
Reference :
I have class Dad with subclass Son. I'd like to create a subclass of Dad and a subclass of Son that overrides a method of Dad.
What would be the best way of doing this without repeating code? I can not modify Dad and Son.
Given...
public class Dad {
public void doSomething() {}
}
public class Son extends Dad {
}
...I'd like to create...
public class DadSubclass extends Dad {
#Overrides
public void doSomething() {
// My code
}
}
public class SonSubclass extends Son {
#Overrides
public void doSomething() {
// My code
}
}
...without repeating // My code.
The obvious solution would be to create a helper class and call it for both, but this is problematic if I want to call protected methods, and I'm not allowed to create the subclasses with the same package.
Is there a better solution?
Create a common helper class and call it.
Assuming your code isn't accessing member variables, I would just put this code in a static utility class. If this isn't the case, you can still do this by passing in a common superclass - that of 'Dad' public static void mycode(Dad d). If you need specific variables in the subclasses themselves, I would rethink your class structure.
What you really want here is something like this:
class DadSonSubclass extends Dad, Son {
public void doSomething() {
//mycode
}
}
This is multiple inheritance, which is not supported by Java. So your only option would be to create a helper/utility class, which is perfectly acceptable. If you need to call protected methods, just pass the Dad object in to the helper class and create public callback methods to access this info.
Maybe better, maybe not, depending on your point of view, but it can certainly be done. Put your code into a helper class, and use a callback to give that helper access to the protected methods it needs:
interface Callback {
void foo();
void bar();
void one();
void two();
}
class Helper {
static void helpMe(Callback callback) {
// My code
}
}
class DadSubclass extends Dad {
#Override
public void doSomething() {
Helper.helpMe(new Callback() {
public void foo() {
DadSubclass.this.foo();
}
public void bar() {
DadSubclass.this.bar();
}
public void one() {
throw new UnsupportedOperationException("one() doesn't exist in Dad");
}
public void two() {
throw new UnsupportedOperationException("two() doesn't exist in Dad");
}
});
}
}
class SonSubclass extends Son {
#Override
public void doSomething() {
Helper.helpMe(new Callback() {
public void foo() {
SonSubclass.this.foo();
}
public void bar() {
SonSubclass.this.bar();
}
public void one() {
SonSubclass.this.one();
}
public void two() {
SonSubclass.this.two();
}
});
}
}
Having this tasteful class
public abstract class CakeSkill
{
//..
boolean cherry=false;
private void finalMandatoryTouch()
{
cherry=true;
}
abstract public void cook();
}
A class that extends it would be something like
class Cheff extends CakeSkill
{
//..
void cook()
{
//..Secret recipe
}
}
But of course this won't work,
finalMandaroryTouch() hasn't been called, then no cake will end with a cherry..
[EDIT]
This one could be a solution
class MemoriousCheff extends CakeSkill
{
//..
void cook()
{
//..Secret recipe
finalMandatoryTouch();
}
}
but requires :
Cheff to have a perfect memory that don't forget to call finalMandatoryTouch()
Making finalMandatoryTouch() to be protected (at least)
[/EDIT]
It would be great! (but no Java) if something like this could be done
abstract public void cook()
{
#implementedMethod
finalMandatoryTouch();
}
How can be implemented this useful functionality ?
Thank you very much
Change cook to a protected method cookImpl then have a public final method called cook:
public final void cook()
{
cookImpl();
finalMandatoryTouch();
}
protected abstract void cookImpl();
That way the subclass only needs to worry about cookImpl, but callers of cook get the cherry on top. Callers not in the same package or class hierarchy won't even see cookImpl, so won't be able to call it directly.
This is the template method pattern, basically.
It's called the Template method pattern.
final public void cook() {
mainCookRecipe();
finalMandatoryTouch();
}
abstract public void mainCookRecipe();
public abstract class CakeSkill {
public void cook() {
doCook();
finalMandatoryTouch();
}
protected abstract doCook();
private finalMandatoryTouch() { ... }
}
Etc.
You could change your cook() method to an actual method and then invoke a separate abstract method as well as your finalMandatoryTouch() method.
In your abstract class:
public void cook() {
specificCook();
finalMandatoryTouch();
}
abstract void specificCook();
It seems that inheritance is not the right way to model your problem. In Java you can only inherit from one class, and since it's also a very static relationship, it limits your chef in the skills he can perform.
A better way would be to use composition. Cooking skills could be strategies that the chef performs:
interface CookingSkill {
void cook();
}
class CakeSkill implements CookingSkill {
private boolean cherry = false;
private void finalMandatoryTouch() {
cherry = true;
}
public void cook() {
//...
finalMandatoryTouch();
}
}
class Chef {
private CookingSkill cookingSkill;
// getters and setters ...
public void cook() {
// ...
cookingSkill.cook();
// ...
}
}
Now you can assign different cooking skills to your chef.