Core JavaScript

Proxy Design Pattern

This Javascript program demonstrates a proxy design pattern. The proxy class waits to load the image until it is requested.

Proxy.html

<!DOCTYPE html>
<html>
	<head>
		<title>XoaX.net's Javascript</title>
		<script type="text/javascript" src="Proxy.js"></script>
	</head>
	<body onload="Initialize()">
	</body>
</html>

Proxy.js

function Initialize() {
	let qBody = document.body;
	
	let qRealImage = new CRealImage("XoaXLogoNew.png");
	let qProxyImage = new CProxyImage("XoaXLogoNew.png");
	
	qBody.appendChild(qRealImage.GetImageElement());
	qBody.appendChild(qProxyImage.GetImageElement());
}

class CAImage {
	constructor() {
		// This can be used to detect instantiation of the abstract class.
		if (this.constructor === CAImage) {
			throw new Error("Instantiated abstract class error: CAImage");
		}
	}
	GetImageElement() {
		throw new Error("Abstract method GetImageElement() must be implemented!");
	}
}

class CRealImage extends CAImage {
	#mqImageElement;
	constructor(sImageFile) {
		super();
		this.#mqImageElement = document.createElement("img");
		this.#mqImageElement.src = sImageFile;
	}
	GetImageElement() {
		return this.#mqImageElement;
	}
}

class CProxyImage extends CAImage {
	#msImageFile
	constructor(sImageFile) {
		super();
		this.#msImageFile = sImageFile;
	}
	GetImageElement() {
		// The image is not loaded until this function is called.
		let qImageElement = document.createElement("img");
		qImageElement.src = this.#msImageFile;
		return qImageElement;
	}
}
 

Output

 
 

© 2007–2026 XoaX.net LLC. All rights reserved.