mcgivrer / monoclass2

This small Java project with only one (master) class is a proof-of-concept of an over simplified java program to deliver maximum feature in a minimum number lines of code, and WITHOUT dependencies out of the JDK itself (but only for test purpose, using JUnit and Cucumber). (Note: subclasses were dispatch into package since july 2022)
MIT License
1 stars 0 forks source link

The Render enhancement #58

Open mcgivrer opened 2 years ago

mcgivrer commented 2 years ago

Refactor the Render with plugin

Here is the opportunity to refactor the Render engine to support extensibility throught Entity nature, declaring a specialized RenderPlugin for each derived type of Entity, allowing new way to implement rendering pipeline.

Render will be renamed to Renderer, and will propose a Map of RenderPlugin implementation according to the Entity class.

public class Renderer{

  Map<Class<? extends Entity>, RenderPlugin> plugins = new ConcurrentHashMap<>();

  public Renderer(Application app){
    this.app = app;

    this.renderers.put(Entity.class,new EntityRenderPlugin());
  }

  public draw(){
    renderingPipeline.values().stream.foreach(e->{
      plugins.get(e.getClass()).draw(this, g,e);
    });
  }

}

The RenderPlugin interface

Any derived entity implmentation will have its corresponding implementation of the RenderPlugin interface.

Interface

public interface RenderPlugin {
    String getRegisteringClass();
    void draw(Renderer r, Graphics2D g, Entity e);
}

Default Implementation

public class EntityRenderPlugin  implements RenderPlugin { 

    public String getRegisteringClass(){
       return Entity.class;
    }

    public  void draw(Renderer r, Graphics2D g, Entity ee) {
            switch (ee.type) {
                case RECTANGLE -> g.fillRect((int) ee.pos.x, (int) ee.pos.y, (int) ee.width, (int) ee.height);
                case ELLIPSE -> g.fillArc((int) ee.pos.x, (int) ee.pos.y, (int) ee.width, (int) ee.height, 0, 360);
                case IMAGE -> {
                    if (ee.getDirection() > 0) {
                        g.drawImage(
                                ee.getImage(),
                                (int) ee.pos.x, (int) ee.pos.y,
                                null);
                    } else {
                        g.drawImage(
                                ee.getImage(),
                                (int) (ee.pos.x + ee.width), (int) ee.pos.y,
                                (int) (-ee.width), (int) ee.height,
                                null);
                    }
                }
                case NONE -> {
                }
            }
        }
}
mcgivrer commented 2 years ago

depends on #57