首先是简单工厂
先建立一个抽象类
1 package gongchang; 2 3 public abstract class Formlaf { 4 5 public abstract void getColor(); 6 }
之后建立产品1
1 package gongchang; 2 3 public class Cilck extends Formlaf{ 4 5 @Override 6 public void getColor() { 7 System.out.println("苹果是红色的"); 8 } 9 10 }
产品2
1 package gongchang; 2 3 public class Clicks extends Formlaf{ 4 5 @Override 6 public void getColor() { 7 System.out.println("橘子是橙色的"); 8 } 9 }
建立一个单例来返回实例
1 package gongchang; 2 3 public class Fromf { 4 private static Formlaf fromlaf;//所有文件的父类 5 private Fromf(){}; 6 7 public static Formlaf getIntss(int a){ 8 if(fromlaf == null){ 9 synchronized (Fromf.class) { 10 if(fromlaf == null){ 11 switch (a) { 12 case 1: 13 //等于1的时候new苹果, 14 return fromlaf = new Cilck(); 15 case 2: 16 //等于2的时候new橘子, 17 return fromlaf = new Clicks(); 18 default: 19 break; 20 } 21 } 22 } 23 } 24 return null; 25 } 26 27 }
建立客户端
1 package gongchang; 2 3 public class kaigong { 4 private static int PING = 1; 5 private static int JU = 2; 6 public static void main(String[] args) { 7 //根据传入的值来判断new什么文件 8 Formlaf formlams = Fromf.getIntss(1); 9 formlams.getColor(); 10 11 } 12 }