Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Extends an abstract class to an enum - Strategy Pattern

I'm trying to use the design pattern Strategy in Java. So, I have an abstract class called Nenuphare that use some interfaces (Mort, AlterationEtat and ModifPV) and I have to create 5 types of Nenuphare. If I'm right, I have to keep Nenuphare as an abstract class is I want to stay in the design pattern Strategy. The easiest way would be to create 5 class that implements Nenuphare and to change Mort, AlterationEtat and ModifPV for each class. But I have to do this with an enum. Unfortunately, enum can't extends a class because it already extends the enum type.

Here's my code for Nenuphare:

public abstract class Nenuphare {
   public int etatVieillissement = 3;
   protected String nom = "Eau";

   protected Mort mort = new MortSubite();
   protected AlterationEtat altetat = new NoAlteration();
   protected ModifPV pv = new NoModifPV();

   public Nenuphare(){}

   public Nenuphare(Mort mort, AlterationEtat altetat, ModifPV pv){
       this.mort = mort;
       this.altetat = altetat;
       this.pv = pv;
   }

   public void death(){
       mort.mort();
   }

   public void alteration(){
       altetat.altEtat();
   }

   public void modificationPV(){
       pv.modifPV();
   }
}

I tried to create my 5 type of Nenuphare this way:

public enum TypeNenuphare extends Nenuphare {
   type1{ this.mort = ..., this.altetat = ..., this.pv = ... }, type2{ ...  }, type3 { ... }, type4 { ... }, type5 { ...};
}

Of course, that doesn't work because of the extends. I thought that I could set Nenuphare as an interface and use implements, but I have to use the design pattern Strategy! Since I'm new to this I don't really know how to proceed.

like image 336
pioupiou1211 Avatar asked Apr 19 '26 18:04

pioupiou1211


1 Answers

Make Nenuphare the enum.

Example:

public enum Strategy{
    STRAT1("Strat1", new Mort1()),
    STRAT2("Strat2", new Mort2()),
    DEFAULT("default", new MortSubite());

    private final String name;
    private final Mort mort;

    public String getName(){ return name;}
    public void death(){mort.mort();} //<- void does not really make sense here.

    Strategy( String pName, Mort pMort ){name = pName; mort = pMort;}
}

Now just exchange "name" for your "death", "alteration", ...

Usage:

System.out.println(Strategy.DEFAULT.getName());

See also: https://docs.oracle.com/javase/tutorial/java/javaOO/enum.html

Sidenote: in an international context, you should use english variable names. That makes it easier for non-french speakers to understand your code.

like image 68
Fildor Avatar answered Apr 21 '26 08:04

Fildor



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!