接口的应用(二)—— 工厂设计模式

接口的应用(二)—— 工厂设计模式(Factory)

首先,如果想确认一个代码是否真的好,有这么几个标准:

  • 客户端调用简单,不需要关注具体的实现细节;
  • 客户端之外的代码修改,不影响用户的使用,即:用户可以 不去关心代码是否变更。

eg.

public interface IFruit {
	public void eat();
}
public class Orange implements IFruit {
	public void eat() {
		System.out.println("吃橘子~");
	}
}
public class Apple implements IFruit {
	public void eat() {
		System.out.println("吃苹果~");
	}
}

public class Test {
	public static void main(String[] args) {
		IFruit fruit = new Apple(); //每次改变水果类型,客户端代码都要修改,这样使得代码的耦合度太高
		fruit.eat();
	}
}

修改:

public interface IFruit {
	public void eat();
}
public class Orange implements IFruit {
	public void eat() {
		System.out.println("吃橘子~");
	}
}
public class Apple implements IFruit {
	public void eat() {
		System.out.println("吃苹果~");
	}
}
//定义一个工厂类,用于获得水果类的实例
public class Factory {
	public static IFruit getInstance(String className) {
		if ("apple".equals(className)) {
			return new Apple();
		}else if ("orange".equals(className)) {
			return new Orange();
		}else 
			return null;
	} 
}
//现在客户端不会看见具体的子类,因为所有的接口对象都是通过Factory类取得的,
//如果日后需要扩充新的IFruit子类对象,则只需要修改Factory类即可,但客户端的调用不会发生变化。

public class Test {
	public static void main(String[] args) {
		Factory f =new Factory();
		IFruit fruit = f.getInstance("apple");
		fruit.eat();
	}
}

运行结果:

吃苹果~
  • 工厂模式结构图:

转载于:https://my.oschina.net/u/3963749/blog/2182955

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值