学完反射和改进的工厂设计模式后

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();

    }

}

以上的代码是关于反射和工厂设计模式的结合案例,我现在看了觉得很兴奋:有点儿意思;

明天去写一遍有关的博文发表下,很久没有写过博文了, 打脸了;

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值