工厂模式(java反射的使用)

在工厂模式中,你不需要关系水果是怎么种出来的,你只要知道水果的名字,将名字交给工厂,你就可以得到水果。

我们首先创建一个水果的接口,所有水果都有一个被吃了的方法,如下代码所示:

package com.fruitInterface.demo;
public interface Fruit {
	public void eaten();
}

我们通过水果的接口定义好具体的水果类(苹果和橘子),在具体的水果方法中,我们实现了“被吃”的方法

package com.fruit.demo;
import com.fruitInterface.demo.Fruit;
public class Apple implements Fruit{
	@Override
	public void eat() {
		System.out.println("I am apple,I am eaten");
		
	}
}

package com.fruit.demo;
import com.fruitInterface.demo.Fruit;
public class Orange implements Fruit{
	@Override
	public void eat() {
		System.out.println("I am orange,I am eaten");
		
	}
}
最后我们的main方法,使用工厂来“吃苹果”

package com.main.demo;
import com.fruit.demo.Apple;
import com.fruitFactory.demo.FactoryDemo;
public class ReflectDemo {
	public static void main(String[] args) throws ClassNotFoundException, InstantiationException, IllegalAccessException {
		// TODO Auto-generated method stub
		Apple apple = (Apple) FactoryDemo.getFruit("com.fruit.demo.Apple");
		apple.eaten();
	}
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值