// Target interface
interface ModernMessageSender {
void sendMessage(String message, String recipient);
}
// Adaptee interface
interface OldMessageSender {
int send(String[] messageData);
}
// Concrete Adaptee
class OldMessageSystem implements OldMessageSender {
@Override
public int send(String[] messageData) {
System.out.println(
"OldMessageSystem: Sending message: "
+ messageData[0] + " to " + messageData[1]
);
return 1; // Success code
}
}
// Adapter
class MessageAdapter implements ModernMessageSender {
private OldMessageSender oldSystem;
public MessageAdapter(OldMessageSender oldSystem) {
this.oldSystem = oldSystem;
}
@Override
public void sendMessage(String message, String recipient) {
String[] messageData = {message, recipient};
int result = oldSystem.send(messageData);
if (result != 1) {
System.out.println("Failed to send message");
}
}
}
// Client
class Main {
public static void main(String[] args) {
OldMessageSender oldSystem = new OldMessageSystem();
ModernMessageSender adapter = new MessageAdapter(oldSystem);
adapter.sendMessage("Hello, World!", "[email protected]");
}
}
// The target interface
interface DisplayAdapter {
void display();
}
// Adaptees
class USB {
void connectWithUsbCable(String data) {
System.out.println("Displaying via USB with data: " + data);
}
}
class HDMI {
void connectWithHdmiCable(int resolution) {
System.out.println(
"Displaying via HDMI with resolution: " + resolution + "p"
);
}
}
class VGA {
void connectWithVgaCable(boolean highQuality) {
System.out.println(
"Displaying via VGA with high quality: " + highQuality
);
}
}
class USBAdapter implements DisplayAdapter {
private USB usb;
private String data;
public USBAdapter(USB usb, String data) {
this.usb = usb;
this.data = data;
}
@Override
public void display() {
usb.connectWithUsbCable(data);
}
}
class HDMIAdapter implements DisplayAdapter {
private HDMI hdmi;
private int resolution;
public HDMIAdapter(HDMI hdmi, int resolution) {
this.hdmi = hdmi;
this.resolution = resolution;
}
@Override
public void display() {
hdmi.connectWithHdmiCable(resolution);
}
}
class VGAAdapter implements DisplayAdapter {
private VGA vga;
private boolean highQuality;
public VGAAdapter(VGA vga, boolean highQuality) {
this.vga = vga;
this.highQuality = highQuality;
}
@Override
public void display() {
vga.connectWithVgaCable(highQuality);
}
}
import java.util.ArrayList;
import java.util.List;
public class Main {
public static void main(String[] args) {
USB usb = new USB();
HDMI hdmi = new HDMI();
VGA vga = new VGA();
List<DisplayAdapter> adapters = new ArrayList<>();
adapters.add(new USBAdapter(usb, "Video Data"));
adapters.add(new HDMIAdapter(hdmi, 1080));
adapters.add(new VGAAdapter(vga, true));
for (DisplayAdapter adapter : adapters) {
adapter.display();
}
}
}