Cake pattern with Java8 possible?

前端 未结 5 1445
无人共我
无人共我 2020-12-24 06:32

I just wonder: with Java 8, and the possibility to add implementation in interfaces (a bit like Scala traits), will it be possible to implement the cake pattern, like we can

5条回答
  •  生来不讨喜
    2020-12-24 07:10

    Maybe you can do something like this in Java 8

    interface DataSource
    {
        String lookup(long id);
    }  
    
    interface RealDataSource extends DataSource
    {
        default String lookup(long id){ return "real#"+id; }
    }  
    
    interface TestDataSource extends DataSource
    {
        default String lookup(long id){ return "test#"+id; }
    }  
    
    abstract class App implements DataSource
    {
        void run(){  print( "data is " + lookup(42) ); }
    }  
    
    
    class RealApp extends App implements RealDataSource {}
    
    new RealApp().run();  // prints "data is real#42"
    
    
    class TestApp extends App implements TestDataSource {}
    
    new TestApp().run();  // prints "data is test#42"
    

    But it is in no way better than the plain/old approach

    interface DataSource
    {
        String lookup(long id);
    }  
    
    class RealDataSource implements DataSource
    {
        String lookup(long id){ return "real#"+id; }
    }  
    
    class TestDataSource implements DataSource
    {
        String lookup(long id){ return "test#"+id; }
    }  
    
    class App
    {
        final DataSource ds;
        App(DataSource ds){ this.ds=ds; }
    
        void run(){  print( "data is " + ds.lookup(42) ); }
    }  
    
    
    new App(new RealDataSource()).run();  // prints "data is real#42"
    
    
    new App(new TestDataSource()).run();  // prints "data is test#42"
    

提交回复
热议问题