发布于 2018-02-19 13:28:17 | 201 次阅读 | 评论: 0 | 来源: 网友投递

这里有新鲜出炉的Java并发编程示例,程序狗速度看过来!

Java程序设计语言

java 是一种可以撰写跨平台应用软件的面向对象的程序设计语言,是由Sun Microsystems公司于1995年5月推出的Java程序设计语言和Java平台(即JavaEE(j2ee), JavaME(j2me), JavaSE(j2se))的总称。


这篇文章主要介绍了java 工厂方法详解及实例代码的相关资料,需要的朋友可以参考下

工厂方法概述

工厂方法模式中抽象工厂类负责定义创建对象的接口,具体对象的创建工作由继承抽象工厂的具体类实现。

优点

客户端不需要在负责对象的创建,从而明确了各个类的职责,如果有新的对象增加,只需要增加一个具体的类和具体的工厂类即可,不影响已有的代码,后期维护容易,增强了系统的扩展性

 缺点

需要额外的编写代码,增加子工作量


public class IntegerDemo {
  public static void main(String[] args) {
    Factory factory = new DogFactory();
    Animal animal = factory.createAnimal();
    animal.eat();
 
    factory = new CatFactory();
    animal = factory.createAnimal();
    animal.eat();
  }
}
 
abstract class Animal {// 抽象类
  public abstract void eat();
}
 
class Dog extends Animal {// 狗
  public void eat() {
    System.out.println("a dog is eatting.");
  }
}
 
class Cat extends Animal {// 猫
  public void eat() {
    System.out.println("a cat is eatting.");
  }
}
 
interface Factory {// 接口
  public abstract Animal createAnimal();
}
 
class DogFactory implements Factory {// 实现接口
  public Animal createAnimal() {
    return new Dog();
  }
}
 
class CatFactory implements Factory {// 实现接口
  public Animal createAnimal() {
    return new Cat();
  }
}

感谢阅读,希望能帮助到大家,谢谢大家对本站的支持!



最新网友评论  共有(0)条评论 发布评论 返回顶部

Copyright © 2007-2017 PHPERZ.COM All Rights Reserved   冀ICP备14009818号  版权声明  广告服务