【Java】 Java常用的几个设计模式实例
一.单例模式
public class SingletonDemo { public static void main(String[] args) { // } } class User1{//饿汉式 User1(){ } private static User1 zs = new User1(); private static User1 getZs(){ return zs; } } class User2{//懒汉式 private User2(){ } private static User2 ls = null; private synchronized static User2 getLs(){//为了线程安全,加上synchronized修饰 if(ls == null){ ls = new User2(); } return ls; } } class User3 {// 双重加锁机制 private User3() { } private static User3 ww = null; private static User3 getWw() { if (ww == null) { synchronized (User3.class) {//只有ww为null的时候,创建过程中加上同步锁 if (ww == null) { ww = new User3(); } } } return ww; } }
二.简单工厂模式
public class SimpleFactoryDemo { public static void main(String[] args) { Factory.create("productA"); Factory.create("ProductB"); } } interface Product { //声明类所需继承的共同接口,也可以是抽象类 } class ProductA implements Product { public ProductA() { System.out.println("ProductA"); } } class ProductB implements Product { public ProductB() { System.out.println("ProductB"); } } class Factory { //可以在工厂类中添加任何你所需要的逻辑 public static Product create(String str) { //生成ProductA if(str.equalsIgnoreCase("ProductA")) { return new ProductA(); } else //生成ProductB if(str.equalsIgnoreCase("ProductB")) { return new ProductB(); } return null; } }
三.工厂方法模式
public class FactoryMethodDemo { public static void main(String[] args) { Factory factory = new FactoryA(); factory.createProduct(); factory = new FactoryB(); factory.createProduct(); } } interface Product{} interface Factory { //声明产生产品类的方法 public Product createProduct(); } class ProductA implements Product { public ProductA() { System.out.println("ProductA"); } } class ProductB implements Product { public ProductB() { System.out.println("ProductB"); } } class FactoryA implements Factory { //实现工厂类的方法生成产品类A public Product createProduct() { return new ProductA(); } } class FactoryB implements Factory { //实现工厂类的方法生成产品类B public Product createProduct() { return new ProductB(); } }
四.抽象工厂模式
public class AbstractFactory { public static void main(String[] args) { Factory factory = new FactoryA(); factory.createGift(); factory.createProduct(); } } interface Product{} interface Gift {}//也可以是抽象类 class ProductA implements Product { public ProductA() { System.out.println("ProductA"); } } class ProductB implements Product { public ProductB() { System.out.println("ProductB"); } } class GiftA implements Gift { public GiftA(){ System.out.println("GiftA"); } } class GiftB implements Gift { public GiftB(){ System.out.println("GiftB"); } } interface Factory { public Product createProduct(); public Gift createGift(); } class FactoryA implements Factory { @Override public Product createProduct(){ return new ProductA(); } @Override public Gift createGift(){ return new GiftA(); } } class FactoryB implements Factory { @Override public Product createProduct(){ return new ProductB(); } @Override public Gift createGift(){ return new GiftB(); } }
五.适配器模式
public class AdapterDemo { public static void main(String[] args) { SmallPort smallPort = new SmallPort() {//手机自带小的接口 public void useSmallPort() { System.out.println("使用的是手机小的接口"); } }; //需要一个大的接口才可以连上电脑,小口转换为大口 BigPort bigPort=new SmallToBig(smallPort); bigPort.useBigPort(); } } interface BigPort { public void useBigPort();//使用的大口 } interface SmallPort { public void useSmallPort();//使用小口 } class SmallToBig implements BigPort{ private SmallPort smallPort;//小口 public SmallToBig(SmallPort smallPort){//获得小口 this.smallPort=smallPort; } @Override public void useBigPort() { this.smallPort.useSmallPort(); //使用小口 } }
六.策略模式
public class StrategyDemo { public static void main(String[] args) { Car smallCar = new SmallCar("路虎","黑色"); Car bussCar = new BussCar("公交车","白色"); Person p1 = new Person("小明", 20); p1.driver(smallCar); p1.driver(bussCar); } } interface CarFunction { void run(); //每辆车有不同的行驶方法 } class Car implements CarFunction { protected String name; //车名字 protected String color; //车颜色 public Car(String name, String color) { this.name = name; this.color = color; } @Override public void run() { System.out.println(color +" " + name +"在行驶。。。"); } } class SmallCar extends Car { public SmallCar(String name, String color) { super(name, color); } @Override public void run() { System.out.println(color +" " + name +"在高速的行驶。。。"); } } class BussCar extends Car{ public BussCar(String name, String color) { super(name, color); } @Override public void run() { System.out.println(color +" " + name +"在缓慢的行驶。。。"); } } class Person { private String name; private Integer age; public void driver(Car car){ System.out.print(name +" "+ age+" 岁 "+" 开着"); car.run(); } public Person(String name,Integer age) { this.name=name; this.age=age; } }
七.代理模式(静态代理)
public class StaticProxyDemo { public static void main(String[] args) { ProxySubject subject = new ProxySubject(new RealSubject()); subject.visit(); } } interface Subject { void visit(); } class RealSubject implements Subject { private String name = "byhieg"; @Override public void visit() { System.out.println(name); } } class ProxySubject implements Subject{ private Subject subject; public ProxySubject(Subject subject) { this.subject = subject; } @Override public void visit() { subject.visit(); } }
八.代理模式(动态代理)
public class DynamicProxyDemo { public static void main(String[] args) { //创建一个实例对象,这个对象是被代理的对象 Person zhangsan = new Student("张三"); //创建一个与代理对象相关联的InvocationHandler InvocationHandler stuHandler = new StuInvocationHandler<Person>(zhangsan); //创建一个代理对象stuProxy来代理zhangsan,代理对象的每个执行方法都会替换执行Invocation中的invoke方法 Person stuProxy = (Person) Proxy.newProxyInstance(Person.class.getClassLoader(), new Class<?>[]{Person.class}, stuHandler); //代理执行上交班费的方法 stuProxy.giveMoney(); } } interface Person { //上交班费 void giveMoney(); } class Student implements Person { private String name; public Student(String name) { this.name = name; } @Override public void giveMoney() { try { //假设数钱花了一秒时间 Thread.sleep(1000); } catch (InterruptedException e) { e.printStackTrace(); } System.out.println(name + "上交班费50元"); } } class MonitorUtil { private static ThreadLocal<Long> tl = new ThreadLocal<>(); public static void start() { tl.set(System.currentTimeMillis()); } //结束时打印耗时 public static void finish(String methodName) { long finishTime = System.currentTimeMillis(); System.out.println(methodName + "方法耗时" + (finishTime - tl.get()) + "ms"); } } class StuInvocationHandler<T> implements InvocationHandler { //invocationHandler持有的被代理对象 T target; public StuInvocationHandler(T target) { this.target = target; } /** * proxy:代表动态代理对象 * method:代表正在执行的方法 * args:代表调用目标方法时传入的实参 */ @Override public Object invoke(Object proxy, Method method, Object[] args) throws Throwable { System.out.println("代理执行" +method.getName() + "方法"); //代理过程中插入监测方法,计算该方法耗时 MonitorUtil.start(); Object result = method.invoke(target, args); MonitorUtil.finish(method.getName()); return result; } }