dart programming

This commit is contained in:
ryanpenn 2019-03-27 10:55:27 +08:00
parent aca7795379
commit 9deeecf9ae
48 changed files with 3018 additions and 25 deletions

2
.gitignore vendored
View File

@ -19,3 +19,5 @@ doc/api/
*.js_
*.js.deps
*.js.map
.DS_Store

21
01_hello_world.dart Normal file
View File

@ -0,0 +1,21 @@
///
/// Hello Dart World
///
void main() {
var lang = "Dart";
/**
*
*
*/
print("Hello $lang World"); //
///
///
///
///
print("This is my first $lang application");
print(3 / 24);
print(true);
}

View File

@ -0,0 +1,84 @@
///
/// build in data types
/// - All data types in Dart are Objects.
///
main(List<String> args) {
// Numbers
var num1 = 100; // type 'int'
int num2 = 200;
double num3 = 30.0;
// float num4; [Error] dart语言没有float关键字使double
print(
"Numbers: num1=$num1, num2=$num2, num3=$num3, num1+num2=${num1 + num2}");
//num1 = num3; [Error] A value of type 'double' can't be assigned to a variable of type 'int'
num1 = num2; // 'var' , num1为'int'
print('');
// Strings
String name = "Dart";
var company = "Google"; // type 'String'
print("$company $name");
//
String lines = 'hello \n'
'dart \n'
'Strings';
print(lines);
//
var s1 = ' "Hello" ';
var s2 = " 'Dart' ";
var s3 = " \"Google\" ";
print("$s1, $s2, $s3");
print('');
// bool
bool isValid = true;
var isAlive = false; // type 'bool'
print("$isValid $isAlive");
print('');
// dynamic
int number; // 'null'
print(number == null ? 'null' : 'not null');
number = 123;
dynamic obj = number;
print("obj is 'int', value is $obj");
obj = "Hello";
print("obj is 'String', value is $obj");
print('');
// final
final langName = 'Dart';
//langName = 'Java'; [Error] a final variable, can only be set once.
// const
const PI = 3.14;
print('$langName, $PI');
print('');
var c1 = Circle(20.0);
var c2 = Circle(30.0);
print("c1: ${c1.radius}");
print("c2: ${c2.radius}");
print("PI: ${Circle.PI}");
}
class Circle {
//const PI = 3.14; [Error] Only static fields can be declared as const.
//
static const PI = 3.14;
// final
final double radius;
Circle(this.radius);
}

View File

@ -0,0 +1,52 @@
///
/// conditional expressions
///
main(List<String> args) {
// if-else
var marks = 70;
if (marks >= 90 && marks < 100) {
print("A+ grade");
} else if (marks >= 80 && marks < 90) {
print("A grade");
} else if (marks >= 70 && marks < 80) {
print("B grade");
} else if (marks >= 60 && marks < 70) {
print("C grade");
} else if (marks > 30 && marks < 60) {
print("D grade");
} else if (marks >= 0 && marks < 30) {
print("You have failed");
} else {
print("Invalid Marks. Please try again !");
}
// condition ? exp1 : exp2
int a = 2;
int b = 3;
int smallNumber = a < b ? a : b;
print("$smallNumber is smaller");
// exp1 ?? exp2
String name;
print(name ?? "Guest User");
// Switch Case Statements: Applicable for only 'int' and 'String'
String grade = 'A';
switch (grade) {
case 'A':
print("Excellent grade of A");
break;
case 'B':
print("Very Good !");
break;
case 'C':
print("Good enough. But work hard");
break;
case 'F':
print("You have failed");
break;
default:
print("Invalid Grade");
}
}

64
04_loop.dart Normal file
View File

@ -0,0 +1,64 @@
///
/// loop
///
main(List<String> args) {
// for loop
for (int i = 1; i <= 10; i++) {
if (i % 2 == 0) {
print(i);
}
}
print('');
// for ..in loop
List planetList = ["Mercury", "Venus", "Earth", "Mars"];
for (String planet in planetList) {
print(planet);
}
print('');
// while loop
var i = 1;
while (i <= 10) {
if (i % 2 == 0) {
print(i);
}
i++;
}
print('');
// do ..while loop
do {
i--;
if (i < 5) {
print(i);
}
} while (i > 0);
print('');
// break labels
breakLabel: for (int x = 1; x < 100; x++) {
for (int y = 1; y < 10; y++) {
print("x=$x, y=$y");
if (x == 1 && y == 3) {
break breakLabel;
}
}
}
print('');
// continue labels
continueLabel: for (var m = 1; m < 3; m++) {
for (var n = 0; n < 10; n++) {
print("m=$m, n=$n");
if (n==2) {
continue continueLabel;
}
}
}
}

58
05_functions.dart Normal file
View File

@ -0,0 +1,58 @@
///
/// functions
///
main(List<String> args) {
var n = add(200, 100);
print(n);
var m = minus(200, 100);
print(m);
output('Hello');
func(1, 2, 3);
func(4, 5);
func(6);
print('');
func2(10, a: 1, b: 2);
func2(0, b: 3);
print('');
fun3(1);
fun3(1, y: 2);
}
int add(int x, int y) {
return x + y;
}
// dynamic
minus(int x, int y) {
return x - y;
}
// '=>' '{return xxxx;}'
output(var s) => print(s);
// Optional Parameters
func(int a, [int b, int c]) {
print("a is $a");
print("b is $b");
print("c is $c");
}
// Optional Named Parameters
func2(int x, {int a, int b}) {
print("x is $x");
print("a is $a");
print("b is $b");
}
// Optional Default Parameters
fun3(int x, {int y = 10}) {
print("x is $x");
print("y is $y");
}

View File

@ -0,0 +1,65 @@
///
/// exception handling
///
main(List<String> args) {
// try ..on,
try {
int result = 12 ~/ 0;
print("The result is $result");
} on IntegerDivisionByZeroException {
print('Cannot divide by Zero');
}
// try ..catch,
try {
int result = 12 ~/ 0;
print("The result is $result");
} catch (e) {
print("The exception thrown is $e");
}
// STACK TRAC
try {
int result = 12 ~/ 0;
print("The result is $result");
} catch (e, s) {
print("The exception thrown is $e");
print("STACK TRACE \n $s");
}
// finally
try {
int result = 12 ~/ 0;
print("The result is $result");
} catch (e) {
print("The exception thrown is $e");
} finally {
print("This is FINALLY Clause and is always executed.");
}
// try ..finally
try {
int result = 12 ~/ 1;
print("The result is $result");
} finally {
print("This is FINALLY Clause and is always executed.");
}
// Custom Exception
try {
throwFunc();
} catch (e) {
print(e);
}
}
class CustomException implements Exception {
@override
String toString() {
return "This is Custom Exception.";
}
}
throwFunc() {
throw CustomException();
}

37
07_class_and_objects.dart Normal file
View File

@ -0,0 +1,37 @@
///
/// class and objects
///
main(List<String> args) {
var student = Student(1);
student.name = "Peter";
student.study();
var tom = Student(2, name: 'Tom');
tom.study();
var robot = Student.myCustomConstructor();
robot.study();
}
class Student {
// 线(private)
int _id = -1;
String name;
//
Student(this._id, {this.name});
//
Student.myCustomConstructor() {
_id = 0;
name = 'Robot';
}
// ()
int get id => _id;
void study() {
print("${this.name}(No.$_id) is now studying");
}
}

87
08_inheritance.dart Normal file
View File

@ -0,0 +1,87 @@
///
/// inheritance.dart
///
main(List<String> args) {
Animal animal = Dog('black');
animal.eat();
(animal as Dog).bark();
if (animal is Duck) {
print('Yes');
} else {
print('No');
}
Duck duck = Duck('white');
duck.eat();
print(duck is Animal);
YellowFlyDuck yellowFlyDuck = YellowFlyDuck();
yellowFlyDuck.eat();
yellowFlyDuck.flyInSky();
yellowFlyDuck.count();
yellowFlyDuck.output();
print(Duck.type);
// print(YellowFlyDuck.type);
}
class Animal {
String color;
eat() {
print('Eat!');
}
}
class Dog extends Animal {
Dog(String color) {
super.color = color;
}
@override
eat() {
print('$color dog eats meat.');
}
void bark() {
print("Bark !");
}
}
class Duck extends Animal {
static String type = "DUCK";
Duck(String color) {
super.color = color;
}
@override
eat() {
print('$color duck eats rice.');
}
}
abstract class Fly {
void flyInSky();
}
class CountableMixin {
int _count = 0;
void count() {
_count++;
}
output() {
print('count: $_count');
}
}
class YellowFlyDuck extends Duck with CountableMixin implements Fly {
YellowFlyDuck() : super('Yellow');
@override
void flyInSky() {
print('$color duck Fly!');
}
}

View File

@ -0,0 +1,43 @@
///
/// lambda nameless function
///
main(List<String> args) {
// Defining Lambda
Function addFunc = (int a, int b) {
var sum = a + b;
print(sum);
};
var addFunc2 = (int a, int b) => a + b;
addFunc(2, 3);
print(addFunc2(3, 4));
var func = addFunc3;
func(1, 2);
var newFunc = makeAddFunc();
newFunc(2, 1);
printAddResult(addFunc2, 5, 5);
}
//
addFunc3(int x, int y) {
var sum = x + y;
print(sum);
}
// 'Function'
Function makeAddFunc() {
return (int x, int y) {
var sum = x + y;
print(sum);
};
}
// 'Function'
printAddResult(Function addFunc, int x, int y) {
var sum = addFunc(x, y);
print(sum);
}

30
10_ closures.dart Normal file
View File

@ -0,0 +1,30 @@
///
/// Closures
///
main(List<String> args) {
// A closure is a function that has access to the parent scope
String message = "Dart is good";
Function showMessage = () {
message = "Dart is awesome";
print(message);
};
showMessage();
print(message);
// A closure is a function object that has access to variables in its lexical scope
Function talk = () {
String msg = "Hi";
Function say = () {
msg = "Hello";
print(msg);
};
return say;
};
Function speak = talk();
speak();
talk()();
}

55
11_collections.dart Normal file
View File

@ -0,0 +1,55 @@
///
/// Collections
///
main(List<String> args) {
// Fixed-length list
List<int> fixedNumList = List(5);
fixedNumList[0] = 10;
fixedNumList[1] = 11;
fixedNumList[2] = 12;
fixedNumList[3] = 13;
fixedNumList[4] = 14;
print(fixedNumList);
fixedNumList[0] = 100;
fixedNumList[1] = null;
print(fixedNumList);
for (var item in fixedNumList) {
print(item);
}
fixedNumList.forEach((element) => print(element ?? 'null value'));
print('length: ${fixedNumList.length}');
print('');
// Growable list
List<String> growableList = ['aaa', 'bbb', 'ccc'];
growableList.add('ddd');
growableList.add('eee');
growableList.addAll(['fff', 'ggg']);
print(growableList);
growableList.remove('ggg');
growableList.removeAt(2);
print(growableList);
growableList.clear();
print(growableList);
growableList..add('111')..add('222')..add('333');
print(growableList);
// Map
Map<String, int> fruits = {"apple": 1, "banana": 2, "guava": 3};
fruits["pear"]=4;
print(fruits);
fruits.forEach((k, v) => print('key:$k,value:$v'));
// Set
Set<String> countries = Set.from(["USA", "INDIA", "CHINA"]); // from a list
countries.add("Japan");
print(countries);
}

11
12_callable_classes.dart Normal file
View File

@ -0,0 +1,11 @@
///
/// callable classes
///
main(List<String> args) {
var call = Callable();
call('Dart');
}
class Callable {
call(String name) => print('call $name');
}

View File

@ -0,0 +1,80 @@
/**
(Factory Pattern)
使
使
*/
main(List<String> args) {
var shapeFactory = ShapeFactory();
// Circle draw
Shape shape1 = shapeFactory.getShape("CIRCLE");
// Circle draw
shape1.draw();
// Rectangle draw
Shape shape2 = shapeFactory.getShape("RECTANGLE");
// Rectangle draw
shape2.draw();
// Square draw
Shape shape3 = shapeFactory.getShape("SQUARE");
// Square draw
shape3.draw();
}
//////////////////////////////////////////////////////////////////
///
///
///
abstract class Shape {
void draw();
}
///
///
///
class Rectangle implements Shape {
@override
void draw() {
print("Inside Rectangle::draw() method.");
}
}
class Square implements Shape {
@override
void draw() {
print("Inside Square::draw() method.");
}
}
class Circle implements Shape {
@override
void draw() {
print("Inside Circle::draw() method.");
}
}
///
///
///
class ShapeFactory {
//使 getShape
Shape getShape(String shapeType) {
switch (shapeType?.toUpperCase()) {
case "CIRCLE":
return Circle();
break;
case "RECTANGLE":
return Rectangle();
break;
case "SQUARE":
return Square();
break;
default:
return null;
}
}
}

View File

@ -0,0 +1,174 @@
/**
(Abstract Factory Pattern)
使
*/
main(List<String> args) {
//
AbstractFactory shapeFactory = FactoryProducer.getFactory("SHAPE");
// Circle
Shape shape1 = shapeFactory.getShape("CIRCLE");
shape1.draw();
// Rectangle
Shape shape2 = shapeFactory.getShape("RECTANGLE");
shape2.draw();
// Square
Shape shape3 = shapeFactory.getShape("SQUARE");
shape3.draw();
//
AbstractFactory colorFactory = FactoryProducer.getFactory("COLOR");
// Red
Color color1 = colorFactory.getColor("RED");
color1.fill();
// Green
Color color2 = colorFactory.getColor("GREEN");
color2.fill();
// Blue
Color color3 = colorFactory.getColor("BLUE");
color3.fill();
}
//////////////////////////////////////////////////////////////////
///
///
///
abstract class Shape {
void draw();
}
///
///
///
class Rectangle implements Shape {
@override
void draw() {
print("Inside Rectangle::draw() method.");
}
}
class Square implements Shape {
@override
void draw() {
print("Inside Square::draw() method.");
}
}
class Circle implements Shape {
@override
void draw() {
print("Inside Circle::draw() method.");
}
}
///
///
///
abstract class Color {
void fill();
}
///
///
///
class Red implements Color {
@override
void fill() {
print("Inside Red::fill() method.");
}
}
class Green implements Color {
@override
void fill() {
print("Inside Green::fill() method.");
}
}
class Blue implements Color {
@override
void fill() {
print("Inside Blue::fill() method.");
}
}
///
/// Color Shape
///
abstract class AbstractFactory {
Color getColor(String color);
Shape getShape(String shape);
}
///
/// AbstractFactory
///
class ShapeFactory extends AbstractFactory {
@override
Shape getShape(String shapeType) {
switch (shapeType?.toUpperCase()) {
case "CIRCLE":
return Circle();
break;
case "RECTANGLE":
return Rectangle();
break;
case "SQUARE":
return Square();
break;
default:
return null;
}
}
@override
Color getColor(String color) {
return null;
}
}
class ColorFactory extends AbstractFactory {
@override
Shape getShape(String shapeType) {
return null;
}
@override
Color getColor(String color) {
switch (color?.toUpperCase()) {
case "RED":
return Red();
break;
case "GREEN":
return Green();
break;
case "BLUE":
return Blue();
break;
default:
return null;
}
}
}
///
/// /
///
class FactoryProducer {
static AbstractFactory getFactory(String choice) {
if (choice == "SHAPE") {
return ShapeFactory();
} else if (choice == "COLOR") {
return ColorFactory();
}
return null;
}
}

View File

@ -0,0 +1,32 @@
/**
Singleton Pattern
访访
使
使
*/
main(List<String> args) {
var s1 = Singleton();
var s2 = Singleton();
print(identical(s1, s2));
print(s1 == s2);
}
//////////////////////////////////////////////////////////////////
///
///
///
class Singleton {
//
static final Singleton _instance = Singleton._();
//
Singleton._();
//
factory Singleton() {
return _instance;
}
}

View File

@ -0,0 +1,176 @@
/**
Builder Pattern
使
"一个复杂对象"
使
*/
main(List<String> args) {
MealBuilder mealBuilder = new MealBuilder();
Meal vegMeal = mealBuilder.prepareVegMeal();
print("Veg Meal");
vegMeal.showItems();
print("Total Cost: ${vegMeal.getCost()}");
Meal nonVegMeal = mealBuilder.prepareNonVegMeal();
print("\n\nNon-Veg Meal");
nonVegMeal.showItems();
print("Total Cost: ${nonVegMeal.getCost()}");
}
//////////////////////////////////////////////////////////////////
///
///
///
abstract class Item {
String name();
Packing packing();
double price();
}
///
///
///
abstract class Packing {
String pack();
}
///
/// Packing
///
class Wrapper implements Packing {
@override
String pack() {
return "Wrapper";
}
}
class Bottle implements Packing {
@override
String pack() {
return "Bottle";
}
}
///
/// Item
///
abstract class Burger implements Item {
@override
Packing packing() {
return new Wrapper();
}
@override
double price();
}
abstract class ColdDrink implements Item {
@override
Packing packing() {
return new Bottle();
}
@override
double price();
}
///
/// Burger ColdDrink
///
class VegBurger extends Burger {
@override
double price() {
return 25.0;
}
@override
String name() {
return "Veg Burger";
}
}
class ChickenBurger extends Burger {
@override
double price() {
return 50.5;
}
@override
String name() {
return "Chicken Burger";
}
}
class Coke extends ColdDrink {
@override
double price() {
return 30.0;
}
@override
String name() {
return "Coke";
}
}
class Pepsi extends ColdDrink {
@override
double price() {
return 35.0;
}
@override
String name() {
return "Pepsi";
}
}
///
/// Meal Item
///
class Meal {
List<Item> _items = List<Item>();
void addItem(Item item) {
_items.add(item);
}
double getCost() {
double cost = 0.0;
for (Item item in _items) {
cost += item.price();
}
return cost;
}
void showItems() {
for (Item item in _items) {
print("Item : ${item.name()}");
print(", Packing : ${item.packing().pack()}");
print(", Price : ${item.price()}");
}
}
}
///
/// MealBuilder builder Meal
///
class MealBuilder {
Meal prepareVegMeal() {
Meal meal = new Meal();
meal.addItem(new VegBurger());
meal.addItem(new Coke());
return meal;
}
Meal prepareNonVegMeal() {
Meal meal = new Meal();
meal.addItem(new ChickenBurger());
meal.addItem(new Pepsi());
return meal;
}
}

View File

@ -0,0 +1,49 @@
/**
Prototype Pattern
使
1
2
3
4便
*/
main(List<String> args) {
Prototype p1 = ConcretePrototype('Tom');
Prototype p2 = p1.clone();
(p1 as ConcretePrototype)?.sayHello();
(p2 as ConcretePrototype)?.sayHello();
print(p1);
print(p2);
}
//////////////////////////////////////////////////////////////////
///
///
///
abstract class Prototype {
Prototype clone();
}
///
///
///
class ConcretePrototype implements Prototype {
String _name;
ConcretePrototype(this._name);
sayHello() {
print('Hello $_name');
}
@override
Prototype clone() {
return ConcretePrototype(_name);
}
}

View File

@ -0,0 +1,115 @@
/**
Adapter Pattern
使
"现存的对象"
使
1使
2使
3
*/
main(List<String> args) {
AudioPlayer audioPlayer = new AudioPlayer();
try {
audioPlayer.play("mp3", "beyond the horizon.mp3");
audioPlayer.play("mp4", "alone.mp4");
audioPlayer.play("vlc", "far far away.vlc");
audioPlayer.play("avi", "mind me.avi");
} catch (e) {
if (e is UnimplementedError) {
print(e.message);
}
}
}
//////////////////////////////////////////////////////////////////
///
///
///
abstract class MediaPlayer {
void play(String audioType, String fileName);
}
abstract class AdvancedMediaPlayer {
void playVlc(String fileName);
void playMp4(String fileName);
}
///
/// AdvancedMediaPlayer
///
class VlcPlayer implements AdvancedMediaPlayer {
@override
void playVlc(String fileName) {
print("Playing vlc file. Name: $fileName");
}
@override
void playMp4(String fileName) {
throw UnimplementedError('当前播放器不能播放mp4.');
}
}
class Mp4Player implements AdvancedMediaPlayer {
@override
void playVlc(String fileName) {
throw UnimplementedError('当前播放器不能播放vlc.');
}
@override
void playMp4(String fileName) {
print("Playing mp4 file. Name: $fileName");
}
}
///
/// MediaPlayer
///
class MediaAdapter implements MediaPlayer {
AdvancedMediaPlayer advancedMusicPlayer;
MediaAdapter(String audioType) {
if (audioType.toUpperCase() == "VLC") {
advancedMusicPlayer = new VlcPlayer();
} else if (audioType.toUpperCase() == "MP4") {
advancedMusicPlayer = new Mp4Player();
}
}
@override
void play(String audioType, String fileName) {
if (audioType.toUpperCase() == "VLC") {
advancedMusicPlayer.playVlc(fileName);
} else if (audioType.toUpperCase() == "MP4") {
advancedMusicPlayer.playMp4(fileName);
}
}
}
///
/// MediaPlayer
///
class AudioPlayer implements MediaPlayer {
MediaAdapter mediaAdapter;
@override
void play(String audioType, String fileName) {
var _type = audioType?.toUpperCase();
// mp3
if (_type == "MP3") {
print("Playing mp3 file. Name: $fileName");
}
//mediaAdapter
else if (_type == "VLC" || _type == "MP4") {
mediaAdapter = new MediaAdapter(audioType);
mediaAdapter.play(audioType, fileName);
} else {
throw UnimplementedError(
"Invalid media. $audioType format not supported");
}
}
}

View File

@ -0,0 +1,65 @@
/**
Bridge
使
使
*/
main(List<String> args) {
Shape redCircle = new Circle(100, 100, 10, new RedCircle());
Shape greenCircle = new Circle(100, 100, 10, new GreenCircle());
redCircle.draw();
greenCircle.draw();
}
//////////////////////////////////////////////////////////////////
///
///
///
abstract class DrawAPI {
void drawCircle(int radius, int x, int y);
}
///
/// DrawAPI
///
class RedCircle implements DrawAPI {
@override
void drawCircle(int radius, int x, int y) {
print("Drawing Circle[ color: red, radius: $radius"
", x: $x, y:$y]");
}
}
class GreenCircle implements DrawAPI {
@override
void drawCircle(int radius, int x, int y) {
print("Drawing Circle[ color: green, radius: $radius"
", x: $x, y:$y]");
}
}
///
/// 使 DrawAPI Shape
///
abstract class Shape {
DrawAPI _drawAPI;
Shape(this._drawAPI);
void draw();
}
///
/// Shape
///
class Circle extends Shape {
int _x, _y, _radius;
Circle(this._x, this._y, this._radius, DrawAPI drawAPI) : super(drawAPI);
void draw() {
_drawAPI.drawCircle(_radius, _x, _y);
}
}

View File

@ -0,0 +1,134 @@
/**
Filter Pattern
使
*/
main(List<String> args) {
List<Person> persons = List<Person>();
persons.add(Person("Robert", "Male", "Single"));
persons.add(Person("John", "Male", "Married"));
persons.add(Person("Laura", "Female", "Married"));
persons.add(Person("Diana", "Female", "Single"));
persons.add(Person("Mike", "Male", "Single"));
persons.add(Person("Bobby", "Male", "Single"));
Filter male = MaleFilter();
Filter female = FemaleFilter();
Filter single = SingleFilter();
Filter singleMale = AndFilter(single, male);
Filter singleOrFemale = OrFilter(single, female);
print("Males: ");
male.filter(persons).forEach((p) => print(p));
print("\nFemales: ");
female.filter(persons).forEach((p) => print(p));
print("\nSingle Males: ");
singleMale.filter(persons).forEach((p) => print(p));
print("\nSingle Or Females: ");
singleOrFemale.filter(persons).forEach((p) => print(p));
}
//////////////////////////////////////////////////////////////////
///
///
///
class Person {
String name;
String gender;
String maritalStatus;
Person(this.name, this.gender, this.maritalStatus);
@override
String toString() {
return 'Person[name="$name", gender="$gender", maritalStatus="$maritalStatus"]';
}
}
///
///
///
abstract class Filter {
List<Person> filter(List<Person> persons);
}
///
/// Filter
///
class MaleFilter implements Filter {
@override
List<Person> filter(List<Person> persons) {
List<Person> personList = List<Person>();
for (Person person in persons) {
if (person.gender.toUpperCase() == "MALE") {
personList.add(person);
}
}
return personList;
}
}
class FemaleFilter implements Filter {
@override
List<Person> filter(List<Person> persons) {
List<Person> personList = List<Person>();
for (Person person in persons) {
if (person.gender.toUpperCase() == "FEMALE") {
personList.add(person);
}
}
return personList;
}
}
class SingleFilter implements Filter {
@override
List<Person> filter(List<Person> persons) {
List<Person> personList = List<Person>();
for (Person person in persons) {
if (person.maritalStatus.toUpperCase() == "SINGLE") {
personList.add(person);
}
}
return personList;
}
}
class AndFilter implements Filter {
Filter _filter1;
Filter _filter2;
AndFilter(this._filter1, this._filter2);
@override
List<Person> filter(List<Person> persons) {
List<Person> personList = _filter1.filter(persons);
return _filter2.filter(personList);
}
}
class OrFilter implements Filter {
Filter _filter1;
Filter _filter2;
OrFilter(this._filter1, this._filter2);
@override
List<Person> filter(List<Person> persons) {
List<Person> personList1 = _filter1.filter(persons);
List<Person> personList2 = _filter1.filter(persons);
for (Person person in personList2) {
if (!personList1.contains(person)) {
personList1.add(person);
}
}
return personList1;
}
}

View File

@ -0,0 +1,74 @@
/**
Composite Pattern
"部分-整体"使使
使
使
1-
2使
*/
main(List<String> args) {
Employee ceo = new Employee("John", "CEO", 30000);
Employee headSales = new Employee("Robert", "Head Sales", 20000);
Employee headMarketing = new Employee("Michel", "Head Marketing", 20000);
Employee clerk1 = new Employee("Laura", "Marketing", 10000);
Employee clerk2 = new Employee("Bob", "Marketing", 10000);
Employee salesExecutive1 = new Employee("Richard", "Sales", 10000);
Employee salesExecutive2 = new Employee("Rob", "Sales", 10000);
ceo.add(headSales);
ceo.add(headMarketing);
headSales.add(salesExecutive1);
headSales.add(salesExecutive2);
headMarketing.add(clerk1);
headMarketing.add(clerk2);
//
print(ceo);
for (Employee headEmployee in ceo.getSubordinates()) {
print(' $headEmployee');
for (Employee employee in headEmployee.getSubordinates()) {
print(' $employee');
}
}
}
//////////////////////////////////////////////////////////////////
///
/// Employee Employee
///
class Employee {
String name;
String dept;
int salary;
List<Employee> subordinates;
//
Employee(this.name, this.dept, this.salary) {
subordinates = List<Employee>();
}
void add(Employee e) {
subordinates.add(e);
}
void remove(Employee e) {
subordinates.remove(e);
}
List<Employee> getSubordinates() {
return subordinates;
}
@override
String toString() {
return 'Employee [ name="$name", dept="$dept", salary="$salary" ]';
}
}

View File

@ -0,0 +1,79 @@
/**
Decorator Pattern
使
使
*/
main(List<String> args) {
Shape circle = new Circle();
Shape redCircle = new RedShapeDecorator(new Circle());
Shape redRectangle = new RedShapeDecorator(new Rectangle());
print("Circle with normal border");
circle.draw();
print("\nCircle of red border");
redCircle.draw();
print("\nRectangle of red border");
redRectangle.draw();
}
//////////////////////////////////////////////////////////////////
///
///
///
abstract class Shape {
void draw();
}
///
///
///
class Rectangle implements Shape {
@override
void draw() {
print("Shape: Rectangle");
}
}
class Circle implements Shape {
@override
void draw() {
print("Shape: Circle");
}
}
///
/// Shape
///
abstract class ShapeDecorator implements Shape {
Shape _decoratedShape;
ShapeDecorator(this._decoratedShape);
void draw() {
_decoratedShape.draw();
}
}
///
/// ShapeDecorator
///
class RedShapeDecorator extends ShapeDecorator {
RedShapeDecorator(Shape decoratedShape) : super(decoratedShape);
@override
void draw() {
_decoratedShape.draw();
setRedBorder(_decoratedShape);
}
void setRedBorder(Shape decoratedShape) {
print("Border Color: Red");
}
}

View File

@ -0,0 +1,76 @@
/**
Facade Pattern
使使
访
使
1"接待员"
2
*/
main(List<String> args) {
ShapeMaker shapeMaker = new ShapeMaker();
shapeMaker.drawCircle();
shapeMaker.drawRectangle();
shapeMaker.drawSquare();
}
//////////////////////////////////////////////////////////////////
///
///
///
abstract class Shape {
void draw();
}
///
///
///
class Rectangle implements Shape {
@override
void draw() {
print("Rectangle::draw()");
}
}
class Square implements Shape {
@override
void draw() {
print("Square::draw()");
}
}
class Circle implements Shape {
@override
void draw() {
print("Circle::draw()");
}
}
///
///
///
class ShapeMaker {
Shape circle;
Shape rectangle;
Shape square;
ShapeMaker() {
circle = Circle();
rectangle = Rectangle();
square = Square();
}
void drawCircle() {
circle.draw();
}
void drawRectangle() {
rectangle.draw();
}
void drawSquare() {
square.draw();
}
}

View File

@ -0,0 +1,73 @@
/**
Flyweight Pattern
使
1
2
3
4
5
*/
import 'dart:math';
main(List<String> args) {
final List<String> colors = ["Red", "Green", "Blue", "White", "Black"];
for (int i = 0; i < 20; ++i) {
Circle circle =
ShapeFactory.getCircle(colors[Random().nextInt(colors.length)]);
circle.x = Random().nextInt(100);
circle.y = Random().nextInt(100);
circle.radius = 100;
circle.draw();
}
}
//////////////////////////////////////////////////////////////////
///
///
///
abstract class Shape {
void draw();
}
///
///
///
class Circle implements Shape {
String color;
int x;
int y;
int radius;
Circle(String color) {
this.color = color;
}
@override
void draw() {
print("Circle: Draw() [Color : $color, x : $x, y :$y, radius :$radius");
}
}
///
///
///
class ShapeFactory {
static final Map<String, Shape> circleMap = Map();
static Shape getCircle(String color) {
Circle circle = circleMap[color] as Circle;
if (circle == null) {
circle = new Circle(color);
circleMap[color] = circle;
print("Creating circle of color : $color");
}
return circle;
}
}

View File

@ -0,0 +1,60 @@
/**
Proxy Pattern
访
访访访访使访访
使访
*/
main(List<String> args) {
Image image = new ProxyImage("dart_logo.png");
//
image.display();
//
image.display();
}
//////////////////////////////////////////////////////////////////
///
///
///
abstract class Image {
void display();
}
///
///
///
class RealImage implements Image {
String fileName;
RealImage(this.fileName) {
loadFromDisk(fileName);
}
@override
void display() {
print("Displaying $fileName");
}
void loadFromDisk(String fileName) {
print("Loading $fileName");
}
}
class ProxyImage implements Image {
RealImage realImage;
String fileName;
ProxyImage(this.fileName);
@override
void display() {
if (realImage == null) {
realImage = RealImage(fileName);
}
realImage.display();
}
}

View File

@ -0,0 +1,96 @@
/**
Chain of Responsibility Pattern
沿
使
*/
main(List<String> args) {
AbstractLogger loggerChain = LoggerFactory.getChainOfLoggers();
loggerChain.logMessage(AbstractLogger.INFO, "This is an information.");
loggerChain.logMessage(
AbstractLogger.DEBUG, "This is a debug level information.");
loggerChain.logMessage(AbstractLogger.ERROR, "This is an error information.");
}
//////////////////////////////////////////////////////////////////
///
///
///
abstract class AbstractLogger {
static int INFO = 1;
static int DEBUG = 2;
static int ERROR = 3;
int _level;
//
AbstractLogger _nextLogger;
void setNextLogger(AbstractLogger nextLogger) {
this._nextLogger = nextLogger;
}
void logMessage(int level, String message) {
if (this._level <= level) {
write(message);
}
if (_nextLogger != null) {
_nextLogger.logMessage(level, message);
}
}
void write(String message);
}
///
///
///
class ConsoleLogger extends AbstractLogger {
ConsoleLogger(int level) {
this._level = level;
}
@override
void write(String message) {
print("Standard Console::Logger: $message");
}
}
class ErrorLogger extends AbstractLogger {
ErrorLogger(int level) {
this._level = level;
}
@override
void write(String message) {
print("Error Console::Logger: $message");
}
}
class FileLogger extends AbstractLogger {
FileLogger(int level) {
this._level = level;
}
@override
void write(String message) {
print("File::Logger: $message");
}
}
class LoggerFactory {
static AbstractLogger getChainOfLoggers() {
AbstractLogger errorLogger = new ErrorLogger(AbstractLogger.ERROR);
AbstractLogger fileLogger = new FileLogger(AbstractLogger.DEBUG);
AbstractLogger consoleLogger = new ConsoleLogger(AbstractLogger.INFO);
errorLogger.setNextLogger(fileLogger);
fileLogger.setNextLogger(consoleLogger);
return errorLogger;
}
}

View File

@ -0,0 +1,86 @@
/**
Command Pattern
使
使"记录、撤销/重做、事务""行为请求者""行为实现者"
*/
main(List<String> args) {
Stock abcStock = new Stock();
BuyStock buyStockOrder = new BuyStock(abcStock);
SellStock sellStockOrder = new SellStock(abcStock);
Broker broker = new Broker();
broker.takeOrder(buyStockOrder);
broker.takeOrder(sellStockOrder);
broker.placeOrders();
}
//////////////////////////////////////////////////////////////////
///
///
///
abstract class Order {
void execute();
}
///
///
///
class Stock {
String name = "ABC";
int quantity = 10;
void buy() {
print("Stock [ Name: $name, Quantity: $quantity ] bought");
}
void sell() {
print("Stock [ Name: $name, Quantity: $quantity ] sold");
}
}
///
/// Order
///
class BuyStock implements Order {
Stock abcStock;
BuyStock(this.abcStock);
void execute() {
abcStock.buy();
}
}
class SellStock implements Order {
Stock abcStock;
SellStock(this.abcStock);
void execute() {
abcStock.sell();
}
}
///
///
///
class Broker {
List<Order> orderList = new List<Order>();
void takeOrder(Order order) {
orderList.add(order);
}
void placeOrders() {
for (Order order in orderList) {
order.execute();
}
orderList.clear();
}
}

View File

@ -0,0 +1,70 @@
/**
Interpreter Pattern
使
使
*/
main(List<String> args) {
Expression robert = TerminalExpression("Robert");
Expression john = TerminalExpression("John");
Expression isMale = OrExpression(robert, john);
print("John is male? ${isMale.interpret('john')}");
Expression julie = TerminalExpression("Julie");
Expression married = TerminalExpression("Married");
Expression isMarriedWoman = AndExpression(julie, married);
print(
"Julie is a married women? ${isMarriedWoman.interpret('Married Julie')}");
}
//////////////////////////////////////////////////////////////////
///
///
///
abstract class Expression {
bool interpret(String context);
}
///
///
///
class TerminalExpression implements Expression {
String _data;
TerminalExpression(this._data);
@override
bool interpret(String context) {
if (context.contains(_data)) {
return true;
}
return false;
}
}
class OrExpression implements Expression {
Expression _expr1;
Expression _expr2;
OrExpression(this._expr1, this._expr2);
@override
bool interpret(String context) {
return _expr1.interpret(context) || _expr2.interpret(context);
}
}
class AndExpression implements Expression {
Expression _expr1;
Expression _expr2;
AndExpression(this._expr1, this._expr2);
@override
bool interpret(String context) {
return _expr1.interpret(context) && _expr2.interpret(context);
}
}

View File

@ -0,0 +1,65 @@
/**
Iterator Pattern
访,
使
*/
main(List<String> args) {
NameRepository namesRepository = new NameRepository();
for (Iterator iter = namesRepository.getIterator(); iter.hasNext();) {
String name = iter.next();
print("Name : $name");
}
}
//////////////////////////////////////////////////////////////////
///
///
///
abstract class Iterator {
bool hasNext();
Object next();
}
abstract class Container {
Iterator getIterator();
}
///
/// Container Iterator NameIterator
///
class NameRepository implements Container {
List<String> names = ["Robert", "John", "Julie", "Lora"];
@override
Iterator getIterator() {
return NameIterator(names);
}
}
class NameIterator implements Iterator {
List<String> _names;
int _index = 0;
NameIterator(this._names);
@override
bool hasNext() {
if (_index < _names.length) {
return true;
}
return false;
}
@override
Object next() {
if (this.hasNext()) {
return _names[_index++];
}
return null;
}
}

View File

@ -0,0 +1,39 @@
/**
Mediator Pattern
使使
使
*/
main(List<String> args) {
User robert = User("Robert");
User john = User("John");
robert.sendMessage("Hi! John!");
john.sendMessage("Hello! Robert!");
}
//////////////////////////////////////////////////////////////////
///
///
///
class ChatRoom {
static void showMessage(User user, String message) {
print("[${user.name}]: $message");
}
}
///
/// user
///
class User {
String name;
User(this.name);
void sendMessage(String message) {
ChatRoom.showMessage(this, message);
}
}

View File

@ -0,0 +1,80 @@
/**
Memento Pattern
使使"后悔药"
*/
main(List<String> args) {
Originator originator = Originator();
CareTaker careTaker = CareTaker();
originator.setState("State #1");
originator.setState("State #2");
careTaker.add(originator.saveStateToMemento());
originator.setState("State #3");
careTaker.add(originator.saveStateToMemento());
originator.setState("State #4");
print("Current State: ${originator.getState()}");
originator.getStateFromMemento(careTaker.get(0));
print("First saved State: ${originator.getState()}");
originator.getStateFromMemento(careTaker.get(1));
print("Second saved State: ${originator.getState()}");
}
//////////////////////////////////////////////////////////////////
///
/// Memento
///
class Memento {
String _state;
Memento(this._state);
String getState() {
return _state;
}
}
///
/// Originator
///
class Originator {
String _state;
void setState(String state) {
this._state = state;
}
String getState() {
return _state;
}
Memento saveStateToMemento() {
return Memento(_state);
}
void getStateFromMemento(Memento memento) {
_state = memento.getState();
}
}
///
/// CareTaker
///
class CareTaker {
List<Memento> _mementoList = List<Memento>();
void add(Memento state) {
_mementoList.add(state);
}
Memento get(int index) {
return _mementoList[index];
}
}

View File

@ -0,0 +1,96 @@
/**
Observer Pattern
使广
使
*/
main(List<String> args) {
Subject subject = Subject();
HexaObserver(subject);
OctalObserver(subject);
BinaryObserver(subject);
print("First state change: 15");
subject.setState(15);
print("\nSecond state change: 10");
subject.setState(10);
}
//////////////////////////////////////////////////////////////////
///
/// Subject
///
class Subject {
List<Observer> _observers = List<Observer>();
int _state;
int getState() {
return _state;
}
void setState(int state) {
this._state = state;
notifyAllObservers();
}
void attach(Observer observer) {
_observers.add(observer);
}
void notifyAllObservers() {
for (Observer observer in _observers) {
observer.update();
}
}
}
///
/// Observer
///
abstract class Observer {
Subject _subject;
void update();
}
///
///
///
class BinaryObserver extends Observer {
BinaryObserver(Subject subject) {
this._subject = subject;
this._subject.attach(this);
}
@override
void update() {
print("Binary String: ${_subject.getState().toRadixString(2)}");
}
}
class OctalObserver extends Observer {
OctalObserver(Subject subject) {
this._subject = subject;
this._subject.attach(this);
}
@override
void update() {
print("Octal String: ${_subject.getState()}");
}
}
class HexaObserver extends Observer {
HexaObserver(Subject subject) {
this._subject = subject;
this._subject.attach(this);
}
@override
void update() {
print("Hex String: ${_subject.getState().toRadixString(16)}");
}
}

View File

@ -0,0 +1,64 @@
/**
State Pattern
使
*/
main(List<String> args) {
Context context = Context();
StartState startState = StartState();
startState.doAction(context);
print(context.state);
StopState stopState = new StopState();
stopState.doAction(context);
print(context.state);
}
//////////////////////////////////////////////////////////////////
///
///
///
abstract class State {
void doAction(Context context);
}
///
/// Context
///
class Context {
State state = null;
Context();
}
///
///
///
class StartState implements State {
void doAction(Context context) {
print("Player is in start state");
context.state = this;
}
@override
String toString() {
return "Start State";
}
}
class StopState implements State {
void doAction(Context context) {
print("Player is in stop state");
context.state = this;
}
@override
String toString() {
return "Stop State";
}
}

View File

@ -0,0 +1,78 @@
/**
Null Object Pattern
NULL
Null
Null
使
*/
main(List<String> args) {
AbstractCustomer customer1 = CustomerFactory.getCustomer("Rob");
AbstractCustomer customer2 = CustomerFactory.getCustomer("Bob");
AbstractCustomer customer3 = CustomerFactory.getCustomer("Julie");
AbstractCustomer customer4 = CustomerFactory.getCustomer("Laura");
print("Customers");
print(customer1.getName());
print(customer2.getName());
print(customer3.getName());
print(customer4.getName());
}
//////////////////////////////////////////////////////////////////
///
///
///
abstract class AbstractCustomer {
String _name;
bool isNil();
String getName();
}
///
///
///
class RealCustomer extends AbstractCustomer {
RealCustomer(String name) {
this._name = name;
}
@override
String getName() {
return _name;
}
@override
bool isNil() {
return false;
}
}
class NullCustomer extends AbstractCustomer {
@override
String getName() {
return "Not Available in Customer Database";
}
@override
bool isNil() {
return true;
}
}
///
/// CustomerFactory
///
class CustomerFactory {
static final List<String> _names = ["Rob", "Joe", "Julie"];
static AbstractCustomer getCustomer(String name) {
for (int i = 0; i < _names.length; i++) {
if (_names[i] == name) {
return new RealCustomer(name);
}
}
return new NullCustomer();
}
}

View File

@ -0,0 +1,64 @@
/**
Strategy Pattern
,, 使
使 if...else
使
*/
main(List<String> args) {
Context context = new Context(new OperationAdd());
print("10 + 5 = ${context.executeStrategy(10, 5)}");
context = new Context(new OperationSubstract());
print("10 - 5 = ${context.executeStrategy(10, 5)}");
context = new Context(new OperationMultiply());
print("10 * 5 = ${context.executeStrategy(10, 5)}");
}
//////////////////////////////////////////////////////////////////
///
///
///
abstract class Strategy {
int doOperation(int num1, int num2);
}
///
///
///
class OperationAdd implements Strategy {
@override
int doOperation(int num1, int num2) {
return num1 + num2;
}
}
class OperationSubstract implements Strategy {
@override
int doOperation(int num1, int num2) {
return num1 - num2;
}
}
class OperationMultiply implements Strategy {
@override
int doOperation(int num1, int num2) {
return num1 * num2;
}
}
///
/// Context
///
class Context {
Strategy _strategy;
Context(this._strategy);
int executeStrategy(int num1, int num2) {
return _strategy.doOperation(num1, num2);
}
}

View File

@ -0,0 +1,75 @@
/**
Template Pattern
使
使
*/
main(List<String> args) {
Game game = new Cricket();
game.play();
print('');
game = new Football();
game.play();
}
//////////////////////////////////////////////////////////////////
///
///
///
abstract class Game {
void initialize();
void startPlay();
void endPlay();
//
void play() {
//
initialize();
//
startPlay();
//
endPlay();
}
}
///
///
///
class Cricket extends Game {
@override
void endPlay() {
print("Cricket Game Finished!");
}
@override
void initialize() {
print("Cricket Game Initialized! Start playing.");
}
@override
void startPlay() {
print("Cricket Game Started. Enjoy the game!");
}
}
class Football extends Game {
@override
void endPlay() {
print("Football Game Finished!");
}
@override
void initialize() {
print("Football Game Initialized! Start playing.");
}
@override
void startPlay() {
print("Football Game Started. Enjoy the game!");
}
}

View File

@ -0,0 +1,86 @@
/**
访Visitor Pattern
使"污染"使访
访访
*/
main(List<String> args) {
ComputerPart computer = Computer();
computer.accept(ComputerPartDisplayVisitor());
}
//////////////////////////////////////////////////////////////////
///
///
///
abstract class ComputerPart {
void accept(ComputerPartVisitor computerPartVisitor);
}
///
///
///
class Keyboard implements ComputerPart {
@override
void accept(ComputerPartVisitor computerPartVisitor) {
computerPartVisitor.visit(this);
}
}
class Monitor implements ComputerPart {
@override
void accept(ComputerPartVisitor computerPartVisitor) {
computerPartVisitor.visit(this);
}
}
class Mouse implements ComputerPart {
@override
void accept(ComputerPartVisitor computerPartVisitor) {
computerPartVisitor.visit(this);
}
}
class Computer implements ComputerPart {
List<ComputerPart> _parts;
Computer() {
_parts = [Mouse(), Keyboard(), Monitor()];
}
@override
void accept(ComputerPartVisitor computerPartVisitor) {
for (int i = 0; i < _parts.length; i++) {
_parts[i].accept(computerPartVisitor);
}
computerPartVisitor.visit(this);
}
}
///
/// 访
///
abstract class ComputerPartVisitor {
void visit(dynamic part);
}
///
/// 访
///
class ComputerPartDisplayVisitor implements ComputerPartVisitor {
@override
void visit(part) {
if (part is Computer) {
print("Displaying Computer.");
} else if (part is Mouse) {
print("Displaying Mouse.");
} else if (part is Keyboard) {
print("Displaying Keyboard.");
} else if (part is Monitor) {
print("Displaying Monitor.");
}
}
}

View File

@ -0,0 +1,71 @@
/**
Model-View-Controller--
Model -
View -
Controller - 使
*/
main(List<String> args) {
Student student = new Student();
student.name = "Robert";
student.rollNo = "10";
//
StudentView view = new StudentView();
StudentController controller = new StudentController(student, view);
controller.updateView();
//
controller.setStudentName("John");
controller.updateView();
}
//////////////////////////////////////////////////////////////////
///
///
///
class Student {
String rollNo;
String name;
}
///
///
///
class StudentView {
void printStudentDetails(String studentName, String studentRollNo) {
print("Student: \nName: $studentName\n Roll No: $studentRollNo");
}
}
///
///
///
class StudentController {
Student _model;
StudentView _view;
StudentController(this._model, this._view);
void setStudentName(String name) {
_model.name = name;
}
String getStudentName() {
return _model.name;
}
void setStudentRollNo(String rollNo) {
_model.rollNo = rollNo;
}
String getStudentRollNo() {
return _model.rollNo;
}
updateView() {
_view.printStudentDetails(_model.name, _model.rollNo);
}
}

View File

@ -0,0 +1,85 @@
/**
访Data Access Object Pattern
访Data Access Object Interface -
访Data Access Object concrete class - xml
/Model Object/Value Object - get/set 使 DAO
*/
main(List<String> args) {
StudentDao studentDao = new StudentDaoImpl();
//
for (Student student in studentDao.getAllStudents()) {
print("Student: [RollNo : ${student.rollNo}, Name : ${student.name} ]");
}
//
Student student = studentDao.getAllStudents()[0];
student.name = "Michael";
studentDao.updateStudent(student);
//
studentDao.getStudent(0);
print("Student: [RollNo : ${student.rollNo}, Name : ${student.name} ]");
}
//////////////////////////////////////////////////////////////////
///
///
///
class Student {
int rollNo;
String name;
Student(this.name, this.rollNo);
}
///
/// 访
///
abstract class StudentDao {
List<Student> getAllStudents();
Student getStudent(int rollNo);
void updateStudent(Student student);
void deleteStudent(Student student);
}
///
///
///
class StudentDaoImpl implements StudentDao {
//
List<Student> _students;
StudentDaoImpl() {
_students = List<Student>();
Student student1 = Student("Robert", 0);
Student student2 = Student("John", 1);
_students.add(student1);
_students.add(student2);
}
@override
void deleteStudent(Student student) {
_students.remove(student.rollNo);
print("Student: Roll No ${student.rollNo}, deleted from database");
}
//
@override
List<Student> getAllStudents() {
return _students;
}
@override
Student getStudent(int rollNo) {
return _students[rollNo];
}
@override
void updateStudent(Student student) {
_students[student.rollNo]?.name = student.name;
print("Student: Roll No ${student.rollNo}, updated in the database");
}
}

View File

@ -0,0 +1,80 @@
/**
Front Controller Pattern
Front Controller - web的应用程序web的应用程序
Dispatcher - 使
View -
*/
main(List<String> args) {
//
// //
FrontController frontController = new FrontController();
frontController.dispatchRequest("HOME");
frontController.dispatchRequest("STUDENT");
}
//////////////////////////////////////////////////////////////////
///
///
///
class HomeView {
void show() {
print("Displaying Home Page");
}
}
class StudentView {
void show() {
print("Displaying Student Page");
}
}
///
/// Dispatcher
///
class Dispatcher {
StudentView _studentView;
HomeView _homeView;
Dispatcher() {
_studentView = StudentView();
_homeView = HomeView();
}
void dispatch(String request) {
if (request.toUpperCase() == "STUDENT") {
_studentView.show();
} else {
_homeView.show();
}
}
}
///
/// FrontController
///
class FrontController {
Dispatcher _dispatcher;
FrontController() {
_dispatcher = Dispatcher();
}
bool _isAuthenticUser() {
print("User is authenticated successfully.");
return true;
}
void _trackRequest(String request) {
print("Page requested: " + request);
}
void dispatchRequest(String request) {
//
_trackRequest(request);
//
if (_isAuthenticUser()) {
_dispatcher.dispatch(request);
}
}
}

107
README.md
View File

@ -1,36 +1,93 @@
# dart_in_action
# Dart语言入门
#### Description
Dart语言入门教程设计模式Dart语言版。
## Dart语言介绍
dart语言是由谷歌公司开发的网络编程语言于2011年10月10日发布。可以通过官网进一步[了解Dart语言](https://www.dartlang.org/guides/language/language-tour)
#### Software Architecture
Software architecture description
## Dart开发环境安装和配置
操作系统Windows、macOS、Linux
下载地址https://flutter.dev/docs/development/tools/sdk/releases?tab=macos
#### Installation
* 以macOS为例解压缩到目录/Users/(macuser)/Dev/flutter/
1. xxxx
2. xxxx
3. xxxx
* 配置:
> vi ~/.bash_profile
#### Instructions
* 编辑:
```bash
# 导出dart
export DART_HOME=/Users/(macuser)/Dev/flutter/flutter/bin/cache/dart-sdk
1. xxxx
2. xxxx
3. xxxx
# 导出flutter
export FLUTTER_HOME=/Users/(macuser)/Dev/flutter/flutter
export PUB_HOSTED_URL=https://pub.flutter-io.cn
export FLUTTER_STORAGE_BASE_URL=https://storage.flutter-io.cn
#### Contribution
export PATH=$DART_HOME/bin:$FLUTTER_HOME/bin:(其他导出项)
```
1. Fork the repository
2. Create Feat_xxx branch
3. Commit your code
4. Create Pull Request
* 校验:
> dart --version
#### Gitee Feature
## 配置编辑器VS Code
* 安装dart支持
![安装dart](screenshots/dart.jpg)
1. You can use Readme\_XXX.md to support different languages, such as Readme\_en.md, Readme\_zh.md
2. Gitee blog [blog.gitee.com](https://blog.gitee.com)
3. Explore open source project [https://gitee.com/explore](https://gitee.com/explore)
4. The most valuable open source project [GVP](https://gitee.com/gvp)
5. The manual of Gitee [https://gitee.com/help](https://gitee.com/help)
6. The most popular members [https://gitee.com/gitee-stars/](https://gitee.com/gitee-stars/)
* 安装代码运行插件
![](screenshots/code_runner.jpg)
![](screenshots/run.jpg)
* 配置debug
![](screenshots/debug.jpg)
* 安装flutter可选
![flutter](screenshots/flutter.jpg)
## 主要内容
1. Hello World
- 运行Dart代码
- Dart语言介绍
2. 内置数据类型
- 内置数据类型
- 变量定义
3. 条件控制语句
- IF ELSE
- 条件表达式
- Switch Case
4. 循环
- for
- while
- do ..while
- break
- continue
- 高级用法
5. 函数
- 函数定义
- 可选参数
- 命名参数
- 默认参数
6. 异常处理
- try ..on
- try ..catch
- try ..finally
- 自定义异常
7. 类和对象
- 定义类
- 类成员可见性
- 属性
- 构造函数
- 自定义构造函数
- 成员变量赋值
8. 继承
- 继承
- extends、implements
- 混入mixin
9. Lambda表达式
- Lambda Expression
- 函数返回Function
- 函数接收Function类型的参数
10. 闭包
11. 集合
12. callable classes
13. 设计模式13-40
- 常用设计模式的Dart实现

5
main.dart Normal file
View File

@ -0,0 +1,5 @@
main(List<String> args) {
var intVar = 123;
var strVar = "Hello";
print("$intVar, $strVar");
}

BIN
screenshots/code_runner.jpg Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 138 KiB

BIN
screenshots/dart.jpg Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 160 KiB

BIN
screenshots/debug.jpg Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 112 KiB

BIN
screenshots/flutter.jpg Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 188 KiB

BIN
screenshots/run.jpg Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 89 KiB