Dart 建構式

Dart 是一個支援 OOP 的程式語言,其建構式也跟大部分物件導向程式大致相同 ex: java。

Factory

在 Dart class constructor 中有提供一個語法糖 factory, 和一般constructor最直觀的差異就是 factory constructor 會回傳一個 instance , 而不是像一般的 constructor 只要傳入值或者對this操作來設定值且不用另外撰寫return相關的語法 。也因為是直接回傳 instance 所以就無法在 factory constructor 內對 this 進行操作。


    void main() {
        final kevin = Person('developer',name:'kevin',age:25,email:'kk@gamil.com');
        final mike = Person.developer(age:25,name:'mike',email:'mm@gamil.com');
        final chris = Person.factory('chris');

        print(kevin.email);
        print(kevin.name);
        print(kevin.age);

        kevin.hello();
        mike.hello();
        chris.hello();
    }

    class Person {
        final String name;
        final int age;
        final String email;
        String position;

        //方法一
        Person(this.position, {this.name,  this.age,  this.email});

        //方法二
        Person.developer({ this.name,  this.age,  this.email}) {
            this.position = 'developer';
        }

        //方法三
        factory Person.factory(String name) {
            return Person('developer', name: name, age: 25, email: 'factory@gamil.com');
        }

        void hello() {
            print('hello, i\'m $name. my position is $position');
        }
    }

    輸出:
        kk@gamil.com
        kevin
        25
        hello, i'm kevin. my position is developer
        hello, i'm mike. my position is developer
        hello, i'm chris. my position is developer

factory 有什麼用途?

大致上有三種 :
1.希望不是每一次呼叫constructor都一定會建立一個新的instance,而是根據情況來決定要不要創建新的instance
2.希望這個class 只能有一個instance(就是單例模式,singleton pattern )
3.不是要回傳這個class而是要回傳這個它的子class

An unhandled error has occurred. Reload 🗙