How to declare factory constructor in abstract classes?

前端 未结 2 1569
别那么骄傲
别那么骄傲 2020-12-18 22:55

I want to declare, but not define a factory constructor in an abstract class.

In my case, I want to create a method that accepts any class that implements a St

2条回答
  •  暖寄归人
    2020-12-18 23:22

    As suggested in the accepted answer, I ended up creating a Serializer type that got implemented by a serializer for each class:

    Turns out, this has several benefits over just having toJson/fromJson on the classes directly:

    • It decouples the serialization logic from the actual classes. That means better code readability because classes only contain methods that relate directly to the class — serializers can even be put into their own files.
    • Currently, extensions can't create constructors. So having serializers separately makes it possible to write serializers for existing classes, like String or Flutter's Color, where you can't just add a fromColor constructor.
    • Both these points combined mean it also works well with code generation — the classes are hand-written and the serializer can be generated in a separate file.

    Code example:

    class Fruit {
      Fruit(this.name, this.color);
    
      final String name;
      final String color;
    }
    
    // in another file
    
    class FruitSerializer extends Serializer {
      Map toJson(Fruit fruit) {
        return ...;
      }
    
      Fruit fromJson(Map data) {
        return Fruit(...);
      }
    }
    

    An then also pass the serializer to the code that needs it:

    someMethod(Serializer serializer, T value) {
      ...
    }
    
    someMethod(FruitSerializer(), someFruit);
    final fruit = recreateFruit(FruitSerializer());
    

    Obviously, you can't pass an object that can't be serialized to the code, because the method expects a Serializer.

提交回复
热议问题