码迷,mamicode.com
首页 > 编程语言 > 详细

java简单的工厂模式

时间:2018-02-12 23:01:48      阅读:187      评论:0      收藏:0      [点我收藏+]

标签:地方   抽象   oid   body   apple   actor   java   pre   div   

定义:专门定义一个类来创建其他类的实例,被创建的实例通常都具有共同的父类和接口。
意图:提供一个类由它负责根据一定的条件创建某一及具体类的实例

//简单工厂,存在不符合开闭原则的地方,可以在参考抽象工厂/工厂方法

//输入苹果,就可以通过工厂直接调用采摘苹果,而不用new一个Apple
public class factoryDemo {

	public static void main(String[] args) {
		// TODO Auto-generated method stu
		Factory factory = new Factory();
		Fruit fruit = factory.getFruit("苹果");
		if(fruit!=null) {
			System.out.println(fruit.get());
		}
		
	}

}

class Factory{
	public static Fruit getFruit(String name) {
		if(name == "苹果") {
			return new Apple();
		}else if(name == "橘子") {
			return new Orange();
		}else {
			return null;
		}
	}
}


interface Fruit{
	String get();
}

class Apple implements Fruit{
	public String get() {
		return "采摘苹果";
	}
}

class Orange implements Fruit{
	public String get() {
		return "采摘橘子";
	}
}

 

java简单的工厂模式

标签:地方   抽象   oid   body   apple   actor   java   pre   div   

原文地址:https://www.cnblogs.com/liubing2018/p/8445688.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!