Dart - Trying to understand the value of 'factory' constructor

前端 未结 3 1935
温柔的废话
温柔的废话 2021-02-10 03:34

If I am understanding correctly:

\"A factory constructor affords an abstract class to be 
    instantiated by another class, despite being abstract.\" 
         


        
3条回答
  •  不思量自难忘°
    2021-02-10 03:52

    The one characteristic of a factory constructor is that the object is not already created at the method start. In the method you can have various mechanisms to create the object, like for example:

    abstract class Animal {
      String makeNoise(String sound);
      String chooseColor(String color);
      factory Animal() {
        var random = new math.Random();
        if (random.nextBool() == true) 
          return new Cat();
        else
          return new Dog();
      }
    }
    

提交回复
热议问题