设计模式之Factory模式 代码初见

ObjectFactory 就是通过Factory建造一个Object,比如说DBConnectionFactory就是专门建造DBConnection的工厂

BuilderFactory就是通过Factory建造一个Builder(就叫Builder模式),比如说DBBuilderFactory就是专门建造DBConnectionBuilder的工厂

PS: 工厂模式和建造者模式可以混用

简单的例子

第一步,创建一个interface

interface Cat
{
  public void meow ();
}

This is a key point, and an important part of the Factory Pattern:

You define a base class type (or in this case an interface), and then have any number of subclasses which implement the contract defined by the base class.

第二步,实现一个实例Class(implement from interface)

class BlackCat implements Cat
{
  public void meow()
  {
    System.out.println("I am a BlackCat");
  }
}

class WhiteCat implements Cat
{
  public void meow()
  {
    System.out.println("I am a WhiteCat");
  }
}

第三步,The Java Factory class

class CatFactory
{
  public static Cat getCat(String criteria)
  {
    if ( criteria.equals("white") )
      return new WhiteCat();
    else if ( criteria.equals("black") )
      return new BlackCat();
    return null;
  }
}

第四步,测试



public class JavaFactoryPatternExample
{
  public static void main(String[] args)
  {
    Cat cat = CatFactory.getCat("white");
    cat.meow();
   }
}

参考


想要看到更多玮哥的学习笔记、考试复习资料、面试准备资料?想要看到IBM工作时期的技术积累和国外初创公司的经验总结?

敬请关注:

玮哥的博客 —— CSDN的传送门

玮哥的博客 —— 简书的传送门

玮哥的博客 —— 博客园的传送门

posted @ 2019-03-09 16:59  vigorpush  阅读(252)  评论(0编辑  收藏  举报