工厂模式代码案例(运用反射)
1、定义一个接口
点击查看代码
package com.bh.shoes;
public interface ShoesLine {
public void make();
}
点击查看代码
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=========");
}
}
点击查看代码
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
点击查看代码
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;
}
}
点击查看代码
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();
}
}
}


浙公网安备 33010602011771号