• Java-马士兵设计模式学习笔记-建造者模式


    一、概述

    二、代码

    1.Animal.java

    1 public interface Animal {
    2     public void bark();
    3 }

    2.Dog.java

    1 public class Dog implements Animal {
    2 
    3     @Override
    4     public void bark() {
    5         System.out.println("Dog wang wang !");
    6     }
    7 
    8 }

    3.Cat.java

    1 public class Cat implements Animal {
    2 
    3     @Override
    4     public void bark() {
    5         System.out.println("cat miao miao");
    6     }
    7 
    8 }

    4.AnimalBuilder.java

     1 package Builder;
     2 
     3 import java.util.ArrayList;
     4 import java.util.List;
     5 
     6 public class AnimalBuilder {
     7 
     8     private static List<Animal> animals = new ArrayList<Animal>();
     9     
    10     public static List<Animal> getDogs(int count){
    11         for(int i = 0; i<count ;i++){
    12             animals.add(new Dog());
    13         }
    14         return animals;
    15     }
    16     
    17     public static List<Animal> getCat(int count){
    18         for(int i = 0; i<count ;i++){
    19             animals.add(new Cat());
    20         }
    21         return animals;
    22     }
    23 }

    5.AnimalFactoryTest.java

     1 package Builder;
     2 
     3 import java.util.List;
     4 
     5 import org.junit.Test;
     6 
     7 public class AnimalFactoryTest {
     8 
     9     @Test
    10     public void test() {
    11         List<Animal> animals = AnimalBuilder.getDogs(3);
    12         for(int i = 0; i<animals.size() ;i++){
    13             animals.get(i).bark();
    14         }
    15     }
    16 
    17 }

    三、运行结果

  • 相关阅读:
    顧客満足度調査
    GeoStTool.dll过滤图层
    GeoStTool.ini相关技术要点
    GeoStTool.dll与RasterServer通信
    hdu 1007 Quoit Design
    hdu 4325 Flowers
    hdu 2516 取石子游戏
    hdu 1006 Tick and Tick
    CodeForces 101A Homework
    ZOJ Problem Set 1879
  • 原文地址:https://www.cnblogs.com/shamgod/p/4594132.html
Copyright © 2020-2023  润新知