package com.it.funny;
import java.lang.reflect.Constructor;
/*
* this snippet of code has perfectly rendered the
* beauty of design: factory and reflection;
*
* and also the essence of reflect is to create an object with
* String, which is brilliant enough as "string" is so comfortable to workwith */
interface Fruit1 {
public void eatfruit();
}
class Orange1 implements Fruit {
private String origin;
private int price;
public Orange1(String origin, int price) {
super();
this.origin = origin;
this.price = price;
}
@Override
public void eatfruit() {
System.out.println("we are here eating fruit");
}
}
class Banana1 implements Fruit {
private String origin;
private int price;
public Banana1(String origin, int price) {
super();
this.origin = origin;
this.price = price;
}
@Override
public void eatfruit() {
System.out.println("banana is a cresent-like fruit form "+origin.toUpperCase()+" sold at the price of $"+price);
}
}
class Factory1 {
public static Fruit getInstance(String obj, String origin,int price) throws Exception {
Class<?> cls = Class.forName("com.it.funny." + obj);
Constructor<?> con = cls.getConstructor(String.class, int.class);
return (Fruit) con.newInstance(origin, price);
}
}
public class FactoryRflectDemo {
public static void main(String[] args) throws Exception {
Fruit f = Factory1.getInstance("Banana1","hubei",123);
f.eatfruit();
}
}
以上的代码是关于反射和工厂设计模式的结合案例,我现在看了觉得很兴奋:有点儿意思;
明天去写一遍有关的博文发表下,很久没有写过博文了, 打脸了;