search
HomeJavajavaTutorialDetailed explanation of graphic code about adapter pattern in Java

Detailed explanation of graphic code about adapter pattern in Java

Jul 24, 2017 pm 03:29 PM
javaGraphics and textadapter

This article mainly introduces the Java adapter mode. The editor thinks it is quite good. Now I will share it with you and give you a reference. Let’s follow the editor and take a look.

1. Concept

The adapter pattern converts one interface into another that the customer wants interface. It allows classes to work together that originally could not work together due to incompatible interfaces.

2. UML

3. More vivid Example

#4. Example analysis

I bought a notebook last year and paired it with a Logitech G1 optical sleeve. What's really annoying is that the mouse of the photoelectric case has a USB interface and the keyboard has a PS2 interface, but my laptop doesn't have a PS2 interface. So I went to the market and bought an adapter.

So, I abstracted several classes.

1.PS2Port (PS2 interface).


2.USBPort (USB interface).


3.PS2ToUSB (object adapter), replace the PS2 interface with a USB interface.


4.TestAdapter (test class), client.


PS2Port



package com.bjpowernode.adapter; 
 
/** 
 * PS2接口,圆口 
 * @author eason 
 * 
 */ 
public interface PS2Port { 
  public void workWithPS2(); 
}

USBPort


##

package com.bjpowernode.adapter; 
 
/** 
 * USB接口,U口 
 * @author eason 
 * 
 */ 
public interface USBPort { 
  public void workWithUSB(); 
}

PS2ToUSB


package com.bjpowernode.adapter; 
 
/** 
 * 对象适配器 
 * 将PS2接口装换成USB接口 
 * 所以此类类型是USB接口(implements USBPort) + 成员变量ps2Port 
 * @author eason 
 * 
 */ 
public class PS2ToUSB implements USBPort{ 
 
  private PS2Port ps2Port; 
   
  public PS2ToUSB(PS2Port ps2Port) { 
    this.ps2Port = ps2Port; 
  } 
   
  @Override 
  public void workWithUSB() { 
    System.out.println("转换的关键在这里,本来是"); 
    ps2Port.workWithPS2(); 
    System.out.println("经过你的转换,现在是USB工作中"); 
  } 
   
}

TestAdapter


##
package com.bjpowernode.adapter; 
 
/** 
 * 测试类 
 * client 
 * @author eason 
 * 
 */ 
public class TestAdapter { 
 
  public static void main(String[] args) { 
    //我现在有一个PS2接口 
    PS2Port ps2Port = new PS2Port() { 
      @Override 
      public void workWithPS2() { 
        System.out.println("PS2工作中"); 
      } 
    }; 
     
    //但是我需要的是一个USB接口啊,对我(client)来说,我只认识USB接口 
    //经过PS2ToUSB的转换,PS2接口变成了USB接口 
    USBPort ps2ToUsbPort = new PS2ToUSB(ps2Port); 
     
    ps2ToUsbPort.workWithUSB(); 
     
  } 
 
}


5. Object Adapter And class adapter

#The above adapter is the object adapter. Let’s look at class adapters again.

PS2ToUSB, just simulate it briefly. Because Java does not allow multiple inheritance, there is no class pattern code in Java, only ideas.


package com.bjpowernode.adapter; 
 
/** 
 * 类适配器 
 * @author eason 
 * 
 */ 
public class PS2ToUSB implements USBPort, PS2Port{ 
 
  //重写workWithUSB,把工作交给workWithPS2 
  @Override 
  public void workWithUSB() { 
    workWithPS2(); 
  } 
   
}

The difference is: the object adapter implements the interface (USB) that the client wants, and has a reference to the adapted object (PS2) internally. Adaptation function is achieved through combination. The class adapter implements the interface (USB) desired by the client and the adapted object interface (PS2), and implements the adaptation function through inheritance.


6. Usage scenarios and usage experience

1. I hope to reuse some existing classes, but the interface is It is inconsistent with the requirements of the reuse environment.

2. In fact, the adapter mode is a bit helpless. In the early design, we should not consider the adapter mode, but should consider refactoring the unified interface.


7. Adapter pattern and decorator pattern


They can both be used to wrap objects, the essential difference is

1. Adapter mode: Convert one interface to another interface.

2. Decorator pattern: Do not change the interface, only add responsibilities.

The above is the detailed content of Detailed explanation of graphic code about adapter pattern in Java. For more information, please follow other related articles on the PHP Chinese website!

Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
JVM performance vs other languagesJVM performance vs other languagesMay 14, 2025 am 12:16 AM

JVM'sperformanceiscompetitivewithotherruntimes,offeringabalanceofspeed,safety,andproductivity.1)JVMusesJITcompilationfordynamicoptimizations.2)C offersnativeperformancebutlacksJVM'ssafetyfeatures.3)Pythonisslowerbuteasiertouse.4)JavaScript'sJITisles

Java Platform Independence: Examples of useJava Platform Independence: Examples of useMay 14, 2025 am 12:14 AM

JavaachievesplatformindependencethroughtheJavaVirtualMachine(JVM),allowingcodetorunonanyplatformwithaJVM.1)Codeiscompiledintobytecode,notmachine-specificcode.2)BytecodeisinterpretedbytheJVM,enablingcross-platformexecution.3)Developersshouldtestacross

JVM Architecture: A Deep Dive into the Java Virtual MachineJVM Architecture: A Deep Dive into the Java Virtual MachineMay 14, 2025 am 12:12 AM

TheJVMisanabstractcomputingmachinecrucialforrunningJavaprogramsduetoitsplatform-independentarchitecture.Itincludes:1)ClassLoaderforloadingclasses,2)RuntimeDataAreafordatastorage,3)ExecutionEnginewithInterpreter,JITCompiler,andGarbageCollectorforbytec

JVM: Is JVM related to the OS?JVM: Is JVM related to the OS?May 14, 2025 am 12:11 AM

JVMhasacloserelationshipwiththeOSasittranslatesJavabytecodeintomachine-specificinstructions,managesmemory,andhandlesgarbagecollection.ThisrelationshipallowsJavatorunonvariousOSenvironments,butitalsopresentschallengeslikedifferentJVMbehaviorsandOS-spe

Java: Write Once, Run Anywhere (WORA) - A Deep Dive into Platform IndependenceJava: Write Once, Run Anywhere (WORA) - A Deep Dive into Platform IndependenceMay 14, 2025 am 12:05 AM

Java implementation "write once, run everywhere" is compiled into bytecode and run on a Java virtual machine (JVM). 1) Write Java code and compile it into bytecode. 2) Bytecode runs on any platform with JVM installed. 3) Use Java native interface (JNI) to handle platform-specific functions. Despite challenges such as JVM consistency and the use of platform-specific libraries, WORA greatly improves development efficiency and deployment flexibility.

Java Platform Independence: Compatibility with different OSJava Platform Independence: Compatibility with different OSMay 13, 2025 am 12:11 AM

JavaachievesplatformindependencethroughtheJavaVirtualMachine(JVM),allowingcodetorunondifferentoperatingsystemswithoutmodification.TheJVMcompilesJavacodeintoplatform-independentbytecode,whichittheninterpretsandexecutesonthespecificOS,abstractingawayOS

What features make java still powerfulWhat features make java still powerfulMay 13, 2025 am 12:05 AM

Javaispowerfulduetoitsplatformindependence,object-orientednature,richstandardlibrary,performancecapabilities,andstrongsecurityfeatures.1)PlatformindependenceallowsapplicationstorunonanydevicesupportingJava.2)Object-orientedprogrammingpromotesmodulara

Top Java Features: A Comprehensive Guide for DevelopersTop Java Features: A Comprehensive Guide for DevelopersMay 13, 2025 am 12:04 AM

The top Java functions include: 1) object-oriented programming, supporting polymorphism, improving code flexibility and maintainability; 2) exception handling mechanism, improving code robustness through try-catch-finally blocks; 3) garbage collection, simplifying memory management; 4) generics, enhancing type safety; 5) ambda expressions and functional programming to make the code more concise and expressive; 6) rich standard libraries, providing optimized data structures and algorithms.

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

Dreamweaver Mac version

Dreamweaver Mac version

Visual web development tools

ZendStudio 13.5.1 Mac

ZendStudio 13.5.1 Mac

Powerful PHP integrated development environment

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

WebStorm Mac version

WebStorm Mac version

Useful JavaScript development tools

SAP NetWeaver Server Adapter for Eclipse

SAP NetWeaver Server Adapter for Eclipse

Integrate Eclipse with SAP NetWeaver application server.