вторник, 6 апреля 2021 г.

Classes

//Dart doesn’t have primitive types!
class _MyClass { //class ("_" - library (file) private)
  var _myProperty = 'default state'; //data member - field
  //_MyClass(); //Default constructor
  void myMethod() { //member function
    print(_myProperty);
  }

  @override
  String toString(){
    return 'MyClass (myProperty: $_myProperty)';
  }
}

class Point {
  int x = 0; //mutable property
  int y = 0; //default value

  Point() : x = 0, y = 0; //def constructor with Initializer list ()
  //Point() : x = 0, y = 0 {} //run before body of the constructor

  Point.def() : this(); //Forwarding constructors

  //named constructor - long form
  Point.set(int x, int y) {
    this.x = x;
    this.y = y;
  }
  //named constructor - short form
  Point.set1(this.x, this.y);
  Point.set2([this.x = 0, this.y = 0]); //optional parameters
  Point.set3({this.x = 0, this.y = 0}); //named parameters

  //old setter method
  bool setter({required int x, required int y}) { //method
    if (x >= 0 && y >= 0) {
      this.x = x;
      this.y = y;
      return true;
    } else {
      return false;
    }
  }

  //old getter method
  String toJson() {
    return '{"x":$x,"y":$y}';
  }

  //new getter - get property
  String get json => '{"x":$x,"y":$y}';

  @override
  String toString() {
    return 'x: $x, y: $y';
  }
}

class Person {
  Person({ //constructor with required named parameters
    required String name,
    required int age,
  }) : assert(name.isNotEmpty), // assert
        assert(age >= 0), // assert
        _name = name, _age = age; //Initializer list for private members

  String _name; //library (file) private
  int _age; //library (file) private

  //factory constructor - can be const, named and unnamed
  factory Person.fromJson(Map<String, Object> json) {
    final pName = json['name'] as String;
    final pAge = json['age'] as int;
    return Person(name: pName, age: pAge);
  }

  @override
  String toString() {
    return 'My name is $_name. I\'m $_age years old.';
  }
}

//Const constructor and immutable class
class Complex {
  const Complex(this.re, this.im); //compile time const
  final double re; //immutable property
  final double im; //- can only be constructed and get but not set!
}

//Named constructor
class Temperature1 {
  Temperature1.celsius(this.celsius);
  Temperature1.farenheit(double farenheit) : celsius = (farenheit - 32) / 1.8;
  double celsius;
}

//Getters and setters
class Temperature2 {
  //constructors
  Temperature2.celsius(this.celsius);
  Temperature2.farenheit(double farenheit) : celsius = (farenheit - 32) / 1.8;
  //property
  double celsius;
  //get property (or calculated property!)
  double get farenheit => celsius * 1.8 +32; //computed member
  //set property
  set farenheit(double faren) => celsius = (faren - 32) / 1.8;
}

//Static methods and variables
class Strings {
  static var welcome = 'Welcome'; //static variable
  static const signIn = 'Sign In'; //static const

  static String greet(String name) => 'Hi, $name';

  static List<Strings> factoryMethod(){ //Static methods
    return <Strings>[];
  }
}

//Singleton - static variable
class MySingleton1 {
  MySingleton1._constructor(); //private named constructor
  static final MySingleton1 instance = MySingleton1._constructor();
}

class MySingleton2 {
  MySingleton2._constructor(); //private named constructor
  static final MySingleton2 _instance = MySingleton2._constructor();
  factory MySingleton2() => _instance; //factory constructor
}

void main() {

  //Objects - instances of classes
  final myObject = _MyClass(); //construct object (reference)
  //var myObject = new _MyClass(); //new - optional
  final sameObject = myObject; //reference to the same object
  print(myObject); //toString()

  myObject._myProperty = 'new state'; //change property
  myObject.myMethod(); //call method

  final p0 = Point(); //default constructor
  print('p0 -> $p0');

  final p1 = Point.set(1, 1) //Cascade operator (..)
  ..x = 5
  ..y = 5;
  print('p1 ${p1.toJson()}'); //old getter method
  print('p1 ${p1.json}'); //new get property

  final p2 = Point.set2(3);
  print('p2 -> $p2');
  final p3 = Point.set3(x: 3);
  print('p3 -> $p3');

  final p4 = Point.def(); //named constructor
  if(p4.setter(x: 3, y: 3)) {
    print('p4.x: ${p4.x}, p4.y: ${p4.y}');
  }
  //constructor assert
  final pers = Person(name: 'Tom', age: 42);
  print(pers);
  //factory constructor
  final json = {'name': 'Mike', 'age': 34};
  final pers1 = Person.fromJson(json); //factory constructor
  print(pers1);

  //Const constructor - immutable objects - good perf!!!
  const complex = Complex(1, 2); // compile time const
  print(complex);
  const listCompl = [ // compile time const
    Complex(3, 4),
    Complex(5, 6),
  ];
  print(listCompl);

  //Named constructor
  final temp1 = Temperature1.celsius(30); //named constructor
  final temp2 = Temperature1.farenheit(90); //named constructor

  //Getters and setters
  print(temp1.celsius); //member
  final temp3 = Temperature2.celsius(30);
  print(temp3.farenheit); //getter
  temp3.farenheit = 93; //setter
  print(temp3.farenheit);

  //Static variables and methods
  print(Strings.welcome);
  print(Strings.signIn);
  print(Strings.greet('Tom'));
  var strings = Strings.factoryMethod(); //static method
  print(strings);

  //Singleton - static instance
  final mySingleton1 = MySingleton1.instance; //explicit singleton
  final mySingleton2 = MySingleton2(); //implicit singleton

}

Комментариев нет:

Отправить комментарий