工厂模式代码案例(运用反射)

1、定义一个接口

点击查看代码
package com.bh.shoes;

public interface ShoesLine {
    public void make();
}
2、定义几个类实现接口
点击查看代码
package com.bh.shoes;

public class NiKeShoes implements ShoesLine{
    @Override
    public void make() {
        System.out.println("NiKe shoes maked=========");
    }
}

点击查看代码
package com.bh.shoes;

public class NBShoes implements ShoesLine{
    @Override
    public void make() {
        System.out.println("NB shoes maked===========");
    }
}

点击查看代码
package com.bh.shoes;

public class LiNingShoes implements ShoesLine{
    @Override
    public void make() {
        System.out.println("LiNing shoes maked========");
    }
}
点击查看代码
package com.bh.shoes;

public class AntaShoes implements ShoesLine{
    @Override
    public void make() {
        System.out.println("Anta shoes maked===========");
    }
}
点击查看代码
package com.bh.shoes;

public class AddidasShoes implements ShoesLine{
    @Override
    public void make() {
        System.out.println("addidas=========");
    }
}
3、配置一个资源文件shoes111.properties
点击查看代码
nike=com.bh.shoes.NikeShoes
nb=com.bh.shoes.NBShoes
anta=com.bh.shoes.AntaShoes
lining=com.bh.shoes.LiNingShoes
addidas=com.bh.shoes.AddidasShoes
4、通过反射定义工厂模式
点击查看代码
package com.bh.factory;

import com.bh.shoes.ShoesLine;

import java.util.ResourceBundle;

public class ShoeFactory {
    //工厂模式
    public ShoesLine makeShoes(String brand){
        ResourceBundle rb = ResourceBundle.getBundle("shoes111");
        String className = rb.getString(brand);

        ShoesLine shoes = null;

        try {
            Class clz = Class.forName(className);
            shoes = (ShoesLine)clz.newInstance();
        } catch (ClassNotFoundException e) {
            throw new RuntimeException(e);
        } catch (InstantiationException e) {
            throw new RuntimeException(e);
        } catch (IllegalAccessException e) {
            throw new RuntimeException(e);
        }
        return shoes;
    }
}

5、测试调用工厂
点击查看代码
package com.bh.factory;

import com.bh.shoes.ShoesLine;

import java.util.Random;

public class FactroyDemo {
    public static void main(String[] args) {
        ShoeFactory shoeFactory = new ShoeFactory();
        Random random = new Random();

        for (int i = 0; i < 10; i++) {
            int i1 = random.nextInt(5);
            String brand=null;
            switch(i1){
                case 0:
                    brand = "nike";
                    break;
                case 1:
                     brand = "nb";
                     break;
                case 2:
                     brand = "anta";
                     break;
                case 3:
                    brand = "lining";
                    break;
                case 4:
                    brand = "addidas";
                    break;

            }
            ShoesLine shoes = shoeFactory.makeShoes(brand);
            shoes.make();
        }
    }
}

6、运行结果

posted @ 2023-05-25 19:36  liangkuan  阅读(24)  评论(0)    收藏  举报