一同养成写作习气!这是我参与「日新计划 4 月更文挑战」的第1天,点击查看活动详情。

builder pattern(创立者形式)适用场景如下: 将杂乱目标的组件完成与组件组合逻辑相互分离,答运用户创立不同组合逻辑,搭配不同产品风格

形式结构

主要由3个主要部分组成

Flutter设计模式(二)-Builder Pattern

  • 1,Director:主要经过builder函数来获取Product
  • 2,Product:通常是一个需要创立的杂乱的目标。
  • 3,builder:创立器,经过一系列步骤,一步一步的创立所需要的目标。

PageRouteBuilder

flutter中,有多种创立器,例如自界说转场动画中,咱们常用的PageRouteBuilder,用来创立Route目标

PageRouteBuilder({
  RouteSettings? settings,
  required this.pageBuilder,
  this.transitionsBuilder = _defaultTransitionsBuilder,
  this.transitionDuration = const Duration(milliseconds: 300),
  this.reverseTransitionDuration = const Duration(milliseconds: 300),
  this.opaque = true,
  this.barrierDismissible = false,
  this.barrierColor,
  this.barrierLabel,
  this.maintainState = true,
  bool fullscreenDialog = false,
})

在实际运用中,能够合作transitionsBuilder自界说转场动画

static Route route() {
  return PageRouteBuilder(
      reverseTransitionDuration: const Duration(milliseconds: 500),
      transitionDuration: const Duration(milliseconds: 500),
      opaque: false,
      pageBuilder: (context, animate, secondaryAnimation) {
        return const BuilderPatternPage();
      },
      transitionsBuilder: (context, animated, secondAnimated, widget) =>
          ScaleTransition(
            alignment: Alignment.bottomCenter,
            filterQuality: FilterQuality.high,
            scale: Tween<double>(begin: 0, end: 1).animate(animated),
            child: widget,
          ));
}

示例代码

接下来,咱们经过创立一个hamburger builder,来展现这种设计形式:

Product

Ingredient是一个笼统类,用来界说汉堡的根底配料。

abstract class Ingredient {
  /// 过敏原
  @protected
  List<String>? allergens;
  /// 姓名
  @protected
  String? name;
  List<String>? getAllergens() {
    return allergens;
  }
  String? getName() {
    return name;
  }
}

然后创立详细的Ingredient类: BigMacBun、RegularBun、BeefPatty、McChickenPatty、BigMacSauce 等来代表莫一种详细的配料。

/// 巨无霸面包
class BigMacBun extends Ingredient {
  BigMacBun() {
    name = 'Big Mac Run';
    allergens = ['Wheat'];
  }
}
/// 惯例面包
class RegularBun extends Ingredient {
  RegularBun() {
    name = "Regular Bun";
    allergens = ['Wheat'];
  }
}
/// 牛肉饼
class BeefPatty extends Ingredient {
  BeefPatty() {
    name = 'Beef Patty';
    allergens = [];
  }
}
class McChickenPatty extends Ingredient {
  McChickenPatty() {
    name = 'McChicken Patty';
    allergens = ['Wheat', 'Cooked in the same fryer that we use...'];
  }
}
/// 巨无霸酱
class BigMacSauce extends Ingredient {
  BigMacSauce() {
    name = 'Big Mac Sauce';
    allergens = ['Egg', 'Soy', 'Wheat'];
  }
}
/// 番茄酱
class Ketchup extends Ingredient {
  Ketchup() {
    name = 'Ketchup';
    allergens = [];
  }
}
/// 蛋黄酱
class Mayonnaise extends Ingredient {
  Mayonnaise() {
    name = 'Mayonnaise';
    allergens = ['egg'];
  }
}
/// 芥末
class Mustard extends Ingredient {
  Mustard() {
    name = 'Mustard';
    allergens = [];
  }
}
/// 洋葱
class Onion extends Ingredient {
  Onion() {
    name = 'Onion';
    allergens = [];
  }
}
/// 奶油
class Cheese extends Ingredient {
  Cheese() {
    name = 'Cheese';
    allergens = ['Milk', 'Soy'];
  }
}
/// 烧烤调味料
class GrillSeasoning extends Ingredient {
  GrillSeasoning() {
    name = 'Grill Seasoning';
    allergens = [];
  }
}
/// 泡菜片
class PickleSlices extends Ingredient {
  PickleSlices() {
    name = 'Pickle Slices';
    allergens = [];
  }
}
/// 生菜丝
class ShreddedLettuce extends Ingredient {
  ShreddedLettuce() {
    name = 'Shredded Lettuce';
    allergens = [];
  }
}

Burger是一个普通的类,用来表示创立器创立的产品

/// Burger
class Burger {
  final List<Ingredient> _ingredients = [];
  double? _price;
  /// 添加配料
  void addIngredient(Ingredient ingredient) {
    _ingredients.add(ingredient);
  }
  /// 获取一切配料
  String getFormattedIngredients() {
    return _ingredients.map((e) => e.getName()).join('.');
  }
  /// 获取一切的过敏原
  String getFormattedAllergens() {
    var allergens = <String>{};
    for (var element in _ingredients) {
      allergens.addAll(element.getAllergens() ?? []);
    }
    return allergens.join('.');
  }
  /// 价格
  String getFormattedPrice() {
    return '$${_price?.toStringAsFixed(2)}';
  }
  void setPrice(double? price) {
    _price = price;
  }
}

Builder

BurgerBuilderBase 是一个笼统类,存储 burger 和 price属性。供给了创立,获取和设置burger价格的默认办法。 同时,也界说了一些笼统办法,需要由详细的生成器来完成这些办法

abstract class BurgerBuilderBase {
  @protected
  Burger? burger;
  @protected
  double? price;
  void createBurger() {
    burger = Burger();
  }
  Burger? getBurger() {
    return burger;
  }
  void setBurgerPrice() {
    burger?.setPrice(price);
  }
  void addBuns();
  void addCheese();
  void addPatties();
  void addSauces();
  void addSeasoning();
  void addVegetables();
}

创立两个详细的Builder,来创立不同类型的产品

class CheeseburgerBuilder extends BurgerBuilderBase {
    ......
}
class BigMacBuilder extends BurgerBuilderBase {
    ......
}

Director

运用BuyerMaker来办理产品的构建过程并回来构建结果。

class BurgerMaker {
  BurgerBuilderBase? burgerBuilder;
  BurgerMaker(this.burgerBuilder);
  void changeBurgerBuilder(BurgerBuilderBase burgerBuilder) {
    this.burgerBuilder = burgerBuilder;
  }
  Burger? getBurger() {
    return burgerBuilder?.getBurger();
  }
  void prepareBurger() {
    burgerBuilder?.createBurger();
    burgerBuilder?.setBurgerPrice();
    burgerBuilder?.addBuns();
    burgerBuilder?.addCheese();
    burgerBuilder?.addPatties();
    burgerBuilder?.addSauces();
    burgerBuilder?.addSeasoning();
    burgerBuilder?.addVegetables();
  }
}

全体的结构如图所示

Flutter设计模式(二)-Builder Pattern

经过 prepareBurger()getBurger办法咱们就能够得到相对应的产品

经过切换不同的创立器咱们能够得到不同类型的产品

Flutter设计模式(二)-Builder Pattern
Flutter设计模式(二)-Builder Pattern

代码我已上传至Gitlab,能够自行下载本文的示例代码 flutter_design_patterns

如果觉得有收获请按如下方式给个 爱心三连::点个赞鼓舞一下。:保藏文章,方便回看哦!。:谈论沟通,相互进步!