一、OOP七大原则
二、创建型模式:
1.单例模式
2.工厂模式
一般都使用简单工厂模式,虽然工厂方法模式可扩展性好,满足开闭原则,但是实际上太过繁琐,从结构复杂度,代码复杂度,管理复杂度,编程复杂度上来看都是简单工厂碾压工厂方法
a、简单工厂模式
b、工厂方法模式
3.抽象工厂模式
4.建造者模式
5.原型模式
、
三、结构性模式
1.适配器模式
//网线类 要被适配的类
public class Adaptee {
public void request(){
System.out.println("链接网线上网");
}
}
//接口类的抽象实现
public interface NetToUsb {
void handlerRequest();
}
//真正的适配器,链接网线,连接USC
public class Adapter implements NetToUsb{
private Adaptee adaptee;
public Adapter(Adaptee adaptee) {
this.adaptee = adaptee;
}
@Override
public void handlerRequest() {
adaptee.request();
}
}
//客户端类 向上网,插不上网线
public class Computer {
public void net(Adapter adapter){
//上网的具体实现,转接头
adapter.handlerRequest();
}
public static void main(String[] args) {
Computer computer = new Computer();
Adaptee adaptee = new Adaptee();
Adapter adapter = new Adapter(adaptee);
computer.net(adapter);
}
}
2.桥接模式
//品牌
public interface Brand {
void info();
}
public class Apple implements Brand {
@Override
public void info() {
System.out.print("苹果");
}
}
public class Lenovo implements Brand {
@Override
public void info() {
System.out.print("联想");
}
}
public abstract class Computer {
//组合,电脑,桥
protected Brand brand;
public Computer(Brand brand) {
this.brand = brand;
}
public void info(){
brand.info();
}
}
class DeskTop extends Computer{
public DeskTop(Brand brand) {
super(brand);
}
@Override
public void info(){
super.info();
System.out.println("台式机");
}
}
class LapTop extends Computer{
public LapTop(Brand brand) {
super(brand);
}
public void info(){
super.info();
System.out.println("笔记本");
}
}
public class Test {
public static void main(String[] args) {
Computer apple = new DeskTop(new Apple());
Computer lenovo = new LapTop(new Lenovo());
apple.info();
lenovo.info();
}
}
3、代理模式
public interface UserService {
void add();
}
public class UserServiceImpl implements UserService{
@Override
public void add() {
System.out.println("添加了方法");
}
}
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;
//自动生成代理类
public class ProxyInvocationHandler implements InvocationHandler {
//代理的接口
private Object target;
public void setTarget(Object target) {
this.target = target;
}
//生成代理类
public Object getProxy(){
return Proxy.newProxyInstance(this.getClass().getClassLoader(), target.getClass().getInterfaces(),this);
}
//处理代理实例,并且返回结果
@Override
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
log("看房");
Object result = method.invoke(target,args);
log("签合同");
return result;
}
private void log(String msg){
System.out.println("执行了"+msg+"方法");
}
}
public class Test {
public static void main(String[] args) {
//真实角色
UserService userService = new UserServiceImpl();
//代理角色
ProxyInvocationHandler pih = new ProxyInvocationHandler();
pih.setTarget(userService);//设置要代理的对象
//动态生成代理类
UserService proxy = (UserService) pih.getProxy();
proxy.add();
}
}