Understanding Factory constructor code example - Dart

后端 未结 4 1592
谎友^
谎友^ 2020-12-04 09:24

I have some niggling questions about factory constructors example mentioned here (https://www.dartlang.org/guides/language/language-tour#factory-constructors). I am aware o

4条回答
  •  庸人自扰
    2020-12-04 09:40

    Complementing Dave's answer, this code shows a clear example when use factory to return a parent related class.

    Take a look a this code from https://codelabs.developers.google.com/codelabs/from-java-to-dart/#3

    You can run this code here. https://dartpad.dartlang.org/63e040a3fd682e191af40f6427eaf9ef

    Make some changes in order to learn how it would work in certain situations, like singletons.

    import 'dart:math';
    
    abstract class Shape {
      factory Shape(String type) {
        if (type == 'circle') return Circle(2);
        if (type == 'square') return Square(2);
        // To trigger exception, don't implement a check for 'triangle'.
        throw 'Can\'t create $type.';
      }
      num get area;
    }
    
    class Circle implements Shape {
      final num radius;
      Circle(this.radius);
      num get area => pi * pow(radius, 2);
    }
    
    class Square implements Shape {
      final num side;
      Square(this.side);
      num get area => pow(side, 2);
    }
    
    class Triangle implements Shape {
      final num side;
      Triangle(this.side);
      num get area => pow(side, 2) / 2;
    }
    
    main() {
      try {
        print(Shape('circle').area);
        print(Shape('square').area);
        print(Shape('triangle').area);
      } catch (err) {
        print(err);
      }
    }
    

提交回复
热议问题